0

I'm trying to read a file (example below), line by line, backwards using Python.

abcd 23ad gh1 n d
gjds 23iu bsddfs ND31 NG 

Note: I'm not trying to read the file from the end to the beginning, but I want to read each line starting from the end, i.e d for line 1, and NG for line 2.

I know that

with open (fileName) as f:
    for line in f:

reads each line from left to right, I want to read it from right to left.

PlsBuffMyBrain
  • 177
  • 1
  • 7

2 Answers2

2

Try this:

with open(fileName, 'r') as f:
    for line in f:
       for item in line.split()[::-1]:
           print(item)
olinox14
  • 6,177
  • 2
  • 22
  • 39
0

If your file is not too big, you can read lines in reverse easily

with open(fileName) as f:
    for line in reversed(f.readlines()):
        # do something

Otherwise, I believe you'd have to use seed.

hspandher
  • 15,934
  • 2
  • 32
  • 45