从多个文件读取和写入python
救命啊?!为什么不在一个目录中搜索多个文件中的“word”,然后在一个新文件中写入包含“word”的整行内容 输入文件如下所示:从多个文件读取和写入python,python,Python,救命啊?!为什么不在一个目录中搜索多个文件中的“word”,然后在一个新文件中写入包含“word”的整行内容 输入文件如下所示: 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
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!')
我希望输出只写一个文件,上面写着:
Blah
Blah
Blah
Blah
Word blah
Blah
废话
废话
您在代码中列出了'Y:/Documents/data'
,但您从'C:/Documents/data/'
读取的内容。这就是问题所在。
试试这个:
Word blah <file name>
Word blah <file name2>
首先解释预期结果、输入/输出示例和错误(如果有)。这些文件是巨大的多行文本文件,每个文件在第50000行上只有一个对“word”的引用。没有错误,但似乎在目录中的任何文件中都找不到提到“word”的内容。但是,它确实打开了正确的文件。输出仅包含数百行“nothere”,因此它看起来确实可以读取和写入文件,但从未找到“word”。这有用吗?
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!')