1

我正在尝试编写一个通过驱动器的脚本。该驱动器的文件夹结构类似于:

| 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

我只是不确定如何检查最后一个文件。该日志将用于查看目录中缺少哪些文件。对此的任何帮助将不胜感激!

4

2 回答 2

2

您可以像这样列出目录中的所有文件:(取自此处

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以使其变得容易,并在完成后记录您的内容。我建议这样做。

于 2012-12-18T02:45:38.620 回答
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")
于 2012-12-18T05:27:20.783 回答