import os
searchquery = 'word'
with open('C:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/data'):
with open('C:/Documents/data/' + filename) as currentFile:
text = currentFile.read()
for line in text:
if searchquery in line:
f.write(searchquery + filename[:-4] + '\n')
else:
print('not here!')
帮助?为什么这不会在目录中搜索“word”的多个文件,然后在新文件中写入包含“word”的整行?
输入文件如下:
Blah
Blah
Blah
Blah
Word blah
Blah
我希望输出只写一个文件:
Word blah <file name>
Word blah <file name2>
答案 0 :(得分:1)
在您的代码中列出'Y:/Documents/data'
,但是您从'C:/Documents/data/'
读取。这就是问题所在。
试试这个:
import os
searchquery = 'word'
with open('C:/Documents/data/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/data/'):
with open('Y:/Documents/data/' + filename) as currentFile:
for line in currentFile:
if searchquery in line:
f.write(searchquery + filename + '\n')
else:
print('not here!')