我有一个目录(名为"Top"),其中包含十个子目录(名为"1“、"2”、"10"),每个子目录都包含大量的文本文件。我希望能够打开子目录2-10中的所有文件,而不需要打开子目录1中的文件。(然后,我将打开子目录1和3-10中的文件,而不打开子目录2中的文件,等等)。现在,我正在尝试使用以下代码读取子目录2-10中的文件,而不读取子目录1中的文件:
import os, fnmatch
def findfiles (path, filter):
for root, dirs, files in os.walk(path):
for file in fnmatch.filter(files, filter):
yield os.path.join(root, file)
for textfile in findfiles(r'C:\\Top', '*.txt'):
if textfile in findfiles(r'C:\\Top\\1', '*.txt'):
pass
else:
filename = os.path.basename(textfile)
print filename问题是这里的if语句(“findfiles中的if文本文件.”)不允许我从文本文件列表中排除子目录1中的文件。你们中有人知道我如何修改我的代码,以便只在子目录2-10中打印这些文件的文件名吗?如果你能在这个问题上提供任何建议,我将不胜感激。
编辑:
如果其他人可能发现它有帮助,我想发布我最终用来解决这个问题的代码:
import os, fnmatch, glob
for file in glob.glob('C:\\Text\\Digital Humanities\\Packages and Tools\\Stanford Packages\\training-the-ner-tagger\\fixed\*\*'):
if not file.startswith('C:\\Text\\Digital Humanities\\Packages and Tools\\Stanford Packages\\training-the-ner-tagger\\fixed\\1\\'):
print file发布于 2013-08-22 00:24:10
将循环更改为:
for textfile in findfiles(r'C:\\Top', '*.txt'):
if not textfile.startswith(r'C:\\Top\\1'):
filename = os.path.basename(textfile)
print filename发布于 2013-08-22 00:27:00
问题就像在常量中使用额外的\一样简单。相反,写:
for textfile in findfiles(r'C:\Top', '*.txt'):
if textfile in findfiles(r'C:\Top\1', '*.txt'):
pass
else:
filename = os.path.basename(textfile)
print filename如果没有使用raw ( \\ )字符串,则\\将是正确的。如果此代码的性能太差,请尝试:
exclude= findfiles(r'C:\Top\1', '*.txt')
for textfile in findfiles(r'C:\Top', '*.txt'):
if textfile in exclude:
pass
else:
filename = os.path.basename(textfile)
print filenamehttps://stackoverflow.com/questions/18369726
复制相似问题