Python 打印文件中的混合文本,并将输出保存到另一个文本文件中
我有一个运行良好的小python脚本:Python 打印文件中的混合文本,并将输出保存到另一个文本文件中,python,Python,我有一个运行良好的小python脚本: with open('xxxxxxx.txt', 'r') as searchfile: for line in searchfile: if 'Neuro' in line: print line 但是我想打印所有带有“neuro”或“brain”或“which”等的行,然后将输出保存到文本文件中-任何非常受欢迎的提示为了读取行,您需要实际调用read()或readlines()方法。在您的例子中,使用r
with open('xxxxxxx.txt', 'r') as searchfile:
for line in searchfile:
if 'Neuro' in line:
print line
但是我想打印所有带有“neuro”或“brain”或“which”等的行,然后将输出保存到文本文件中-任何非常受欢迎的提示为了读取行,您需要实际调用read()或readlines()方法。在您的例子中,使用readlines(),它返回文件中每一行的列表。然后你可以循环通过它 例如:
lines = searchfile.readlines()
strings = ("neuro", "brain", "whatever")
for line in lines:
if any(s in line for s in strings):
print(line)
然后,您可以将要写入的行列表传递给另一个文件。您可以在启用写入标志的情况下打开一个新文件:
strings = ("neuro", "brain", "whatever")
with open('xxxxxxx.txt', 'r') as searchfile, open('target_file.txt', 'w') as output:
for line in searchfile:
if any(s in line.lower() for s in strings):
output.write(line)
实际上,默认情况下,
searchfile
(与任何类似于对象的文本文件一样)会公开iterable接口,不需要执行readline位。这是否回答了您的问题?