关键字搜索和导出到输出文档在Python中的.txt文件

问题描述:

我想写一个Python函数,读取文本文件的每一行,并搜索关键字:如果关键字在行我是试图将该行导出为新的文本文档。这本质上会创建一种过滤文本行的方式。这是我到目前为止:关键字搜索和导出到输出文档在Python中的.txt文件

#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 

任何帮助将不胜感激,因为我没有遇到语法错误,但我的输出文件是空白的。

您的循环应该是这个样子:

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

+0

哦,好吧,这是有道理的。谢谢您的帮助! –