简体   繁体   中英

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

I am trying to build an app in Python that will open a file, and find a specific keyword and read what is after that keyword only in that line. If that value matches any element in the input list it should append the said files name (with extension; in this case text.txt) to another list.

This is my code:

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!")

But always prints It doesn't work. Even if there is a match. Let alone append the filename to the list.

Sample file:

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

Sample input: VMTester

your code looks ok in principle; it's just that you append a file object to your file_list if you do file_list.append(current_file) . The with context will even close it so no point to do that... Also, you could use any to check if any of the input_list items is in the current line . Assuming the seach should stop as soon as a match is encountered, you can use break to skip all further lines. A modified version of your code could look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM