-1

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

Aarush
  • 37
  • 7
  • How does `lines[-3]` get you the *last* line? – Scott Hunter Jan 01 '21 at 14:01
  • 1
    Does this answer your question? [Print string to text file](https://stackoverflow.com/questions/5214578/print-string-to-text-file) – ChrisGPT was on strike Jan 01 '21 at 14:03
  • So your problem is **you don't know how to write to a file** and instead of printing in to the terminal you want to write it to a file, right? – Countour-Integral Jan 01 '21 at 14:06
  • @ScottHunter . The input file had last 3 lines space so i gave like that . I dont know how to delete the empty spaces in the text file because as I have more than 10000 text files as input. – Aarush Jan 01 '21 at 14:10
  • @Countour-Integral , yes exactly . Print is giving me the line in terminal but when i try to write it is not writing all the 10000 files last line . But only the last read file. – Aarush Jan 01 '21 at 14:12
  • It isn't clear what your asking: you want to know how to write to a file?; you want to know how to redirect print to a file? ; you want to find the last line of a file? ; you want to know why only the last line of the **last** file is written? - [“Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question). – wwii Jan 01 '21 at 14:12
  • Im trying to print the last line of the test files . The code gives me the result correctly in terminal . But i want to redirect those to a text file . SO if i have 1000 input text file Im expecting the output file to have the last line of all the input files. – Aarush Jan 01 '21 at 14:18
  • Your [mre] does not show how you are writing to the *new* file - the way you open it could be the problem. From your mre, we can't tell what you are doing wrong and I am tempted to close it as a duplicate of [Directing print output to a .txt file](https://stackoverflow.com/questions/36571560/directing-print-output-to-a-txt-file) or [How to redirect 'print' output to a file using python?](https://stackoverflow.com/questions/7152762/how-to-redirect-print-output-to-a-file-using-python). – wwii Jan 01 '21 at 14:23
  • Does [Writing to a file in a for loop](https://stackoverflow.com/questions/11198718/writing-to-a-file-in-a-for-loop) answer your question? – wwii Jan 01 '21 at 14:25
  • I figured it out myself . Thanks for the responses . – Aarush Jan 01 '21 at 14:28
  • What was the problem? – wwii Jan 01 '21 at 14:28
  • @ScottHunter The original poster wrote `lines[-3]` because the last few lines of the file are blank. They are trying to omit all blank lines. They could write `line = line.strip()` after that, write something like `if len(line) < 1: [blah, blah, blah]` – Toothpick Anemone Jan 01 '21 at 14:51

2 Answers2

1

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)
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
0

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!

Jaysmito Mukherjee
  • 1,467
  • 2
  • 10
  • 29