如何在 Python 中对目录中的所有文件或仅基于 args 的单个文件执行功能



我正在处理一个小脚本,它"粉碎"单个文件(将文件的字节归零(,我正在尝试制作它,以便我可以根据它是否通过命令行接收 -file 或 -directory 标志/arg 来粉碎目录中的每个文件。 它适用于单个文件,但我得到:

IsADirectoryError: [Errno 21] 'Path/To/Directory' error when trying to use it on all files in a directory.我已经尝试了几种安排循环的方法,以便它们工作,但到目前为止还没有。我希望这里有人可以帮助我纠正这一点。

我有argparser设置,因此-F file, -D directory, -s srcpath, -i iterations和与bar有关的任何事情都只是我的进度条,它显示了脚本在运行时的过程有多远。

这是我的代码:

parser= argparse.ArgumentParser()
parser.add_argument('-F', '--file', action=store_true)
parser.add_argument('-D', '--directory', action=store_true)
parser.add_argument('-s', '--source', required=True, type=str)
parser.add_argument('-i', '--iterations', required=True, type=int)
args = parser.parse_args()
bar = Bar ("Progress: ", max=args.iterations)
srcpath = "path/to/file/"
def shredfile(source, filebytes):
with open(source, 'r+b') as f:
byte = f.read(1)
while byte:
f.write(filebytes)
byte = f.read(1)
zeros = ("0000000").encode('UTF-8')
if args.file:
x=0
for x in range (args.iterations):
shredfile(srcpath, zeros)
bar.next()
bar.finish()
print("Completed")
if args.directory:
for d in os.listdir(srcpath):
x=0
for x in range (args.iterations):
shredfile(srcpath, zeros)
bar.next()
bar.finish()
print("Completed")

os.listdir返回目录中的文件名

for f in os.listdir(srcpath):
full_path = os.path.join(f, srcpath)
...
shredfile(full_path, zeros)
...
print("Completed")

我猜你不能粉碎一个目录,而只能切碎单个文件。

shredfile(os.path.join(srcpath, d), zeros)

这将是执行此操作的正确方法。您只需要添加进度条和参数解析等部分。 您还需要添加一些 try-except 块来控制 OSError 上发生的事情,例如权限被拒绝和类似的东西。


import sys
import os
def shredfile (source, filebytes=16*""):
f = open(source, "rb")
f.seek(0, 2)
size = f.tell()
f.close()
if len(filebytes)>size:
chunk = filebytes[:size]
else:
chunk = filebytes
f = open(source, "wb")
l = len(chunk)
n = 0
while n+l<size:
f.write(chunk)
n += l
# Ensure that file is overwritten to the end if size/len(filebytes)*len(filebytes) is not equal to size
chunk = filebytes[:size-f.tell()]
if chunk: f.write(chunk)
f.close()
def shreddir (source, filebytes=16*"", recurse=0):
for x in os.listdir(source):
path = os.path.join(source, x)
if os.path.isfile(path):
shredfile(path, filebytes)
continue
if recurse:
shreddir(path, filebytes, 1)
def shred (source, filebytes=16*"", recurse=0):
if os.path.isdir(source):
shreddir(source, filebytes, recurse)
return
shredfile(source, filebytes)
if len(sys.argv)>1:
print "Are you sure you want to shred '%s'?" % sys.argv[-1],
c = raw_input("(Yes/No?) ").lower()
if c=="yes":
shred(sys.argv[-1])
# Here you can iterate shred as many times as you want.
# Also you may choose to recurse into subdirectories which would be what you want if you need whole directory shredded

相关内容

最新更新