我有一个文件,我正在搜索和打印结果到一个文件。我想知道是否有可能修改下面的代码来读取多个搜索词,即打印任何一行,其中有“test”或“hello”(用户将指定),但让Python为每个搜索词创建一个新的输出文件
也就是说,Ofile1将保存所有包含“test”的行 Ofile2将保留所有包含“hello”等的行
f = open('file3.txt') #input file
term = raw_input("What would you like to search for?") #takes an input to be searched
for line in f:
if term in line:
print (line) #print line of matched term
f.close() #close file
这有可能吗
用空格分隔术语。然后使用for循环遍历所有术语
例如:
基于@new user code(改进了一些错误),您可以这样做:
也许你可以认为最好打开文件一次,每行检查一些术语。根据术语的数量,它的效率会有所不同,如果您愿意,可以使用非常大的文件来检查执行时间并了解更多
相关问题 更多 >
编程相关推荐