获取每个目录的文件(Py)

2024-10-03 15:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个小脚本,加密位于特定路径后的每个文件。在我的例子中,脚本realpath。。。 在第一个文件夹(脚本目录)中工作正常,但是当我转到下一个目录时,它会尝试将cd放入位于第二个目录层的文件中。 所以树看起来像[file,file,folder[file,file],file,file]

(我知道,脚本和密钥也会被加密,但我还是懒得这么做。。。很抱歉我的英语很差,希望你能理解我:P)

我的代码:

import os
import Crypto
from Crypto.PublicKey import RSA

def cryptFilesInFolder(currentDir):
    content_list = os.listdir(currentDir)
    print content_list
    print '[+] Start encrypting files in Dir: ' + currentDir
    for filename in content_list:
        print '[+] Encrypting ' + filename
        crypt(filename, key, currentDir)

def crypt(filename, key, currentDir):
    try:
        f = open(filename, 'r')
        fileString = f.read()
        f.close()
        print '[+] Encrypting file: ' + filename + ' with 4096 bytes'
        encryptedFileString = key.publickey().encrypt(fileString, 4096)
        f = open (filename, 'w')
        f.write(str(encryptedFileString)) #write ciphertext to file
        f.close()
    except IOError:
        print '[!] File was a folder'
        cryptFilesInFolder(currentDir + '/' + filename)

print '[+] Startet Crypting'
print '[+] Reading Key'
f = open('mykey.pem','r')
key = RSA.importKey(f.read())
f.close()
print '[+] Key imported'
print '[+] Setting Root Directory'
rootDir = os.path.realpath(__file__)
print 'Root Directory set'
print '[+] Starting encryption in folder: '
cryptFilesInFolder(os.path.dirname(os.path.realpath(__file__)))
print '[+] Finished \n\n\n'

错误消息:

^{pr2}$

Tags: keyinimport目录脚本oscontentfolder
1条回答
网友
1楼 · 发布于 2024-10-03 15:29:58

似乎您正在尝试对文件夹中的每个文件运行某个命令,包括该文件夹(递归)子文件夹中的任何文件。在

在这种情况下,您需要使用^{},它将递归地遍历给定的目录并生成(current directory, directories, files)的元组。在

import os
for (root, dirs, files) in os.walk(rootDir):
    # In each iteration, files will contain the list of files in the directory,
    # where directories are traversed recursively.
    map(lambda f: crypt(f, key, root), files)

^{}函数只是将crypt(好吧,是crypt的包装)应用到每个项目。在

map(lambda f: crypt(f, key, root), files)在功能上等同于:

^{pr2}$

相关问题 更多 >