我正在尝试编写一个通过驱动器的脚本。该驱动器具有与此类似的文件夹结构:
| Folder 1
+--->Folder 1.txt
+--->Folder 1.nfo
| Folder 2
+--->Folder 2.doc
+--->Folder 2.nfo
+--->Folder 2.xls
| Folder 3
+--->Folder 3.txt
+--->Folder 3.nfo
较旧的 我想要做的是读取目录中的每个文件,然后当我完成目录时,我想写一个日志到文本文件。我目前使用以下内容打开每个目录和文件:
logfile = open("log.txt")
for path, subdirs, files in os.walk(directory):
txtfile = 0
docfile = 0
xlsfile = 0
nfofile = 0
for name in files:
file = os.path.join(path, name)
if file.endswith('.txt'):
txtfile = 1
elif file.endswith('.doc'):
docfile = 1
elif file.endswith('.xls'):
xlsfile = 1
elif file.endswith('.nfo'):
nfofile = 1
# if all files in a specific directory (Folder 1, Folder 2, etc) have been read, write line to log.txt
我只是不确定如何检查最后一个文件。该日志将用于查看目录中缺少的文件。任何有关这方面的帮助将不胜感激!
答案 0 :(得分:1)
您可以列出目录中的所有文件:(取自here)
from os import listdir
from os.path import isfile, join
files = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
然后检查您的文件:
if file == files[-1]: # do stuff
或者,您可以遍历files
以简化操作,完成后,记录您的内容。我建议这样做。
答案 1 :(得分:0)
看看是否有效:
import os
import os.path as opath
for path, dirs, files in os.walk(directory):
exts = {}
for fn, ext in (opath.splitext(f) for f in files):
exts[ext] = exts.get(ext, 0) + 1
with open(opath.join(path, "extlog.txt"), "w") as log:
log.write("\n".join(("%s|%s" % (k, v)) for k, v in exts.items()) + "\n")