首页 > 解决方案 > 如何打开文本文件并查找一行中特定单词之后写的内容并将该文件名附加到 Python 中的列表中

问题描述

我正在尝试在 Python 中构建一个应用程序,该应用程序将打开一个文件,并找到一个特定的关键字并仅在该行中读取该关键字之后的内容。如果该值与输入列表中的任何元素匹配,则应将所述文件名(带有扩展名;在本例中为 text.txt)附加到另一个列表中。

这是我的代码:

input_list=input("> ").split(", ") # The input list
file_list=[] # Where the filenames should be appended

with open("/path/to/file.txt") as current_file:
    for line in current_file:
        if line[5::] in input_list:
            print("It works!")
            file_list.append(current_file)
        elif line[9::] in input_list:
            print("It works!")
        elif line[12::] in input_list:
            print("It works!")
        else:
            print("It doesn't work!")

但总是打印它不起作用。即使有比赛。更不用说将文件名附加到列表中了。

示例文件:

Value=@3a
Execute=abc
Name=VMTester #line[5::] should remove the "Name=" and also Name could also be "Name[en_us]=" or just "Name[bn]="
Comment=This is a samplefile

样本输入: VMTester

标签: python

解决方案


您的代码原则上看起来不错;只是file_list如果你这样做,你将一个文件对象附加到你的file_list.append(current_file). 上下文甚至会关闭它,with所以没有必要这样做......此外,您可以使用它any来检查是否有任何input_list项目是in当前的line. 假设一旦遇到匹配就停止搜索,您可以使用break跳过所有其他行。您的代码的修改版本可能看起来像

input_files = ["/path/to/file.txt"] # you can add more files to search here...
input_list = input("> ").split(", ")
file_list = []
extracted_words = []

for file in input_files: # added loop through all files to search
    with open(file, 'r') as current_file:
        for line in current_file:
            if any(w in line for w in input_list):
                print("It works!")
                # append the file name:
                file_list.append(file)
                # append the matched word (strip newline character):
                extracted_words.append(line.split('=')[1:][0].strip())
                break
        print("It doesn't work!") # looped through all lines, no match encountered

推荐阅读