0

So, I have a txt file with the word 'QWE'. I am trying to print it reversed, but [::-1} does not work in this case.

file = open('10asciitxt.txt', 'r') 
      
    while 1: 
      
    # read by character 
    char = file.read(1)
    if not char:  
        break  
    res=128-ord(char)  
    print(char," = ",ord(char),"| 128 - ",ord(char)," = ",res," Res: ",chr(res))
file.close()

Output:

Q  =  81 | 128 -  81  =  47  Res:  /
W  =  87 | 128 -  87  =  41  Res:  )
E  =  69 | 128 -  69  =  59  Res:  ;

Expected Output:

E  =  69 | 128 -  69  =  59  Res:  ;
W  =  87 | 128 -  87  =  41  Res:  )
Q  =  81 | 128 -  81  =  47  Res:  /
NoemonGR
  • 59
  • 1
  • 9

3 Answers3

2

using readlines() and read() helps as it saves the text file in list then you can simply reverse it.

file = open('sample.txt', 'r') 
ls = file.readlines() #creates list of lines
ls.reverse() # directly reverse it
print('/n'.join(ls)) #join it by specific operator

ref:https://www.w3schools.com/python/ref_file_readlines.asp

Yash
  • 71
  • 4
1

You can read the entire file at once and then iterate backwards

file = open('10asciitxt.txt', 'r') 

file_contents = file.readlines()

            #### Reverse File Contents
for line in file_contents[::-1]:
    for char in line:
        if not char.isspace():
           res=128-ord(char)  
           print(char," = ",ord(char),"| 128 - ",ord(char)," = ",res," Res: ",chr(res))

file.close()
Vaebhav
  • 4,672
  • 1
  • 13
  • 33
  • His code read the file byte-by-byte, not by-line. You should change `readlines()` to just `read()`. – kwkt Jan 09 '21 at 02:58
  • Noemon I realised it now , its a byte by byte read rather than line by line , updated the answer , @kwkt - thanks for pointing it out – Vaebhav Jan 09 '21 at 03:03
1

How to read a file in reverse order? could help.

Or you can read all characters of the file into a list if its size is not huge, as following:

chars = [char for char in open('10asciitxt.txt').read()]
for char in chars[::-1]:
    i = ord(char)
    res = 128 - i  
    print(char, " = ", i, "| 128 - ", i, " = " , res, " Res: ", chr(res))
Yang Liu
  • 346
  • 1
  • 6