0

I want to reverse characters in a line of a text file, sample text file content is as below,

ABCDEF
EFGHIJ
013236

Expected output is,

FEDCBA
JIHGFE
632310

I have tried using readlines(), but I ended up reversing the order of lines as well. Please suggest

randomir
  • 17,989
  • 1
  • 40
  • 55

2 Answers2

0

Iterate line by line and then reverse characters in each line. After that join them at last to produce desired output.

>>> with open('new.txt', 'r') as f:
...     print(''.join([line[::-1] for line in f.readlines()]))
... 

FEDCBA
JIHGFE
632310
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
0

You can iterate through a file and get the reverse of each line with slicing:

with open('yourfile.txt') as file:
    for line in file:
        print(line.strip('\n')[::-1])
iz_
  • 15,923
  • 3
  • 25
  • 40