簡體   English   中英

如何打開文本文件並查找在一行中的特定單詞和 append 文件名之后寫入的內容到 Python 中的列表

[英]How to open a text file and find what is written after a specific word in a line and append that files name to a list in Python

我正在嘗試在 Python 中構建一個應用程序,該應用程序將打開一個文件,並找到一個特定的關鍵字並僅在該行中讀取該關鍵字之后的內容。 如果該值與輸入列表中的任何元素匹配,則它應該 append 將所述文件名(帶有擴展名;在本例中為 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!")

但總是打印它不起作用。 即使有比賽。 更不用說 append 的文件名了。

示例文件:

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

您的代碼原則上看起來不錯; 只是你 append 一個文件 object 到你的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM