简体   繁体   中英

Search text file and save result to another text file

I am pretty new to python and have only very limited programming skills with it. I hope you can help me here.

I have a large text file and I'm searching it for a specific word. Every line with this word needs to be stored to another txt file.

I can search the file and print the result in the console but not to a different file. How can I manage that?

f = open("/tmp/LostShots/LostShots.txt", "r")

searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "Lost" in line: 
        for l in searchlines[i:i+3]: print l,
        print

f.close()

Thx Jan

Use with context manager, do not use readlines() since it will read the whole contents of a file into a list. Instead iterate over file object line by line and see if a specific word is there; if yes - write to the output file:

with open("/tmp/LostShots/LostShots.txt", "r") as input_file, \ 
     open('results.txt', 'w') as output_file:

    for line in input_file:
        if "Lost" in line:
            output_file.write(line) 

Note that for python < 2.7, you cannot have multiple items in with :

with open("/tmp/LostShots/LostShots.txt", "r") as input_file:
    with open('results.txt', 'w') as output_file:

        for line in input_file:
            if "Lost" in line:
                output_file.write(line) 

To correctly match words in general, you need regular expressions; a simple word in line check also matches blablaLostblabla which I assume you don't want:

import re

with open("/tmp/LostShots/LostShots.txt", "r") as input_file, \ 
        open('results.txt', 'w') as output_file:

    output_file.writelines(line for line in input_file
                           if re.match(r'.*\bLost\b', line)

or you can use a more wordy

    for line in input_file:
        if re.match(r'.*\bLost\b', line)):
            output_file.write(line)

As a side note, you should be using os.path.join to make paths; also, for working with temporary files in a cross-platform manner, see the functions in the tempfile module.

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