我试图编写一个python函数来读取文本文件的每一行并搜索关键字:如果关键字在行中,我试图将该行导出为新的文本文件。这基本上会创建一种过滤文本行的方法。以下是我到目前为止的情况:
#trying to filter and print a line that contains a keyword in a csv or txt
file
import subprocess
import csv
def findandsearch(word):
textfile=open('textHCPC17_CONTR_ANWEB.txt', 'r+')
#openign the selected text file
outputfile=input('CMSOUTPUT.txt')
#classifying an ouput file
word=s'education' #designating a keyword
for line in textfile:
textfile.readline()
if word in textfile: #creating if clause
print('this is a match') #printing that this is match
outputfile.write(word) #I want to write the selected line of the text in the output file
textfile.close() #closing the original file
print(word) #I want to print the results
return #ending function
任何帮助都会受到赞赏,因为我没有遇到语法错误,但我的输出文件是空白的。
答案 0 :(得分:0)
你的for循环应该是这样的:
for line in textfile:
if word in line:
print('blahblah')
outputfile.write(line)
textfile.close()
print(line)
return
在你的if子句中你有字符串和文件对象之间的比较,它甚至听起来很奇怪:-S
在python文档中,这个解决方案的解释更好:python doc - input and output