我正在zipfile
用来创建目录中所有文件的存档(递归,同时保留包括空文件夹的目录结构),并希望该过程跳过列表中指定的文件名。
这是os。遍历目录并将所有包含的文件和目录添加到归档文件中的基本功能。
def zip_dir(path):
zipname = str(path.rsplit('/')[-1]) + '.zip'
with zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED) as zf:
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
for file_or_dir in files + dirs:
zf.write(os.path.join(root, file_or_dir),
os.path.relpath(os.path.join(root, file_or_dir),
os.path.join(path, os.path.pardir)))
elif os.path.isfile(filepath):
zf.write(os.path.basename(filepath))
zf.printdir()
zf.close()
我们可以看到代码也应该具有处理单个文件的能力,但是它主要是与我们感兴趣的目录有关的部分。
现在,我们有一个要从文件名列表中排除的文件名列表。
skiplist = ['.DS_Store', 'tempfile.tmp']
什么是实现这一目标的最佳和最清洁的方法?
我尝试使用zip
哪种方法有些成功,但由于某种原因导致它排除了空文件夹(应包括空文件夹)。我不确定为什么会这样。
skiplist = ['.DS_Store', 'tempfile.tmp']
for root, dirs, files in os.walk(path):
for (file_or_dir, skipname) in zip(files + dirs, skiplist):
if skipname not in file_or_dir:
zf.write(os.path.join(root, file_or_dir),
os.path.relpath(os.path.join(root, file_or_dir),
os.path.join(path, os.path.pardir)))
看看是否有人对增加跳过特定文件扩展名的功能有一个聪明的主意,这也许会很有趣,.endswith('.png')
但我不太确定如何将其与现有的跳过列表结合在一起。
我还要感谢您对该功能的其他一般性评论,以及它是否确实可以按预期工作而不会感到惊讶,以及任何有关优化或改进的建议。
您可以简单地检查文件是否不在skiplist
:
skiplist = {'.DS_Store', 'tempfile.tmp'}
for root, dirs, files in os.walk(path):
for file in files + dirs:
if file not in skiplist:
zf.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, os.path.pardir)))
这样可以确保中的文件skiplist
不会添加到存档中。
另一种优化是制作skiplist
一个集,以防万一它变得非常大,并且您希望使用列表来进行恒定时间O(1)查找而不是线性O(N)查找。
您可以在TimeComplexity上对此进行更多研究,该报告显示了数据结构上各种Python操作的时间复杂性。
至于扩展名,您可以os.path.splitext()
用来提取扩展名并使用与上述相同的逻辑:
from os.path import splitext
extensions = {'.png', '.txt'}
for root, dirs, files in os.walk(path):
for file in files:
_, extension = splitext(file)
if extension not in extensions:
zf.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, os.path.pardir)))
如果要组合上述功能,则可以分别处理文件和目录的逻辑:
from os.path import splitext
extensions = {'.png', '.txt'}
skiplist = {'.DS_Store', 'tempfile.tmp'}
for root, dirs, files in os.walk(path):
for file in files:
_, extension = splitext(file)
if file not in skiplist and extension not in extensions:
zf.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, os.path.pardir)))
for directory in dirs:
if directory not in skiplist:
zf.write(os.path.join(root, directory),
os.path.relpath(os.path.join(root, directory),
os.path.join(path, os.path.pardir)))
注意:上面的代码片段不能单独使用,您需要将当前的代码进行编织才能使用这些想法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句