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)