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

2024-04-23 10:47:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个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

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


Tags: csvthetoinimporttxtthatline
1条回答
网友
1楼 · 发布于 2024-04-23 10:47:57

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

相关问题 更多 >