简体   繁体   中英

write output from print to a file in python

I have a code that reads multiple text files and print the last line.

from glob import glob
text_files = glob('C:/Input/*.txt')
for file_name in text_files:
       with open(file_name, 'r+') as f:
           lines = f.read().splitlines()
           last_line = lines[-3]
           print (last_line)

I want to redirect the print to an output txt file, so that i will check the sentence. Also the txt files has multiple lines of space. I want to delete all the empty lines and get the last line of the file to an output file. When i try to write it is writing only the last read file. Not all files last line is written.

Can someone help?

Thanks, Aarush

Instead of just print, do something like this:

print(last_line)
with open('output.txt', 'w') as fout:
    fout.write(last_line)

Or you could also append to the file!

I think you have two separate questions.
Next time you use stack overflow, if you have multiple questions, please post them separately.

Question 1

How do I re-direct the output from the print function to a file?
For example, consider a hello world program:

 print("hello world")

How do we create a file (named something like text_file.txt ) in the current working directory, and output the print statements to that file?

ANSWER 1

Writing output from the print function to a file is simple to do:

with open ('test_file.txt', 'w') as out_file:
    print("hello world", file=out_file)    

Note that print function accepts a special keyword-argument named " file "
You must write file=f in order to pass f as input to the print function.

QUESTION 2

How do I get the last non-blank line from s file? I have an input file which has lots of line-feeds, carriage-returns, and space characters at the end of. We need to ignore blank lines, and retrieve the last lien of the file which contains at least one character which is not a white-space character.

Answer 2

def get_last_line(file_stream):   
    for line in map(str, reversed(iter(file_stream))):

        # `strip()` removes all leading a trailing white-space characters
        # `strip()` removes `\n`, `\r`, `\t`, space chars, etc...

        line = line.strip()
        
        if len(line) > 0:
            return line

     # if the file contains nothing but blank lines
     # return the empty string
     return ""

You can process multiple files like so:

file_names = ["input_1.txt", "input_2.txt", "input_3.txt"]

with  open ('out_file.txt', 'w') as out_file:
    for file_name in file_names:
       with open(file_name, 'r') as read_file:
           last_line = get_last_line(read_file)
           print (last_line, file=out_file)

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