1

I have been trying to figure this out for a while and I just cant

I want to reverse a file that looks like this

Hello there
My name is
How are you

And by reversing it i mean I want it to look like this after

there Hello
is name My
you are How

I have tried with

 lines = []
with open('test.txt', "r") as f:
    lines = f.readlines()

with open('testrev.txt', 'w') as f:
    for line in reversed(lines):
        f.write(line)

and by adding

f.write(line[::-1])

Im sorry but i just cannot figure this out and help would be greatly appriciated

nleif
  • 11
  • 1
  • Hint: don't read from and write to the file at the same time. Either user an other output file or read, process, reopen and write. – Klaus D. Sep 13 '18 at 13:00
  • The duplicate discusses reversing the words, and not the letters, of a given line. The short-short version, in Python, is `" ".join(line.split()[::-1]) + "\n"` – Martijn Pieters Sep 13 '18 at 13:16
  • @KlausD.: They are reading from one file, then writing to another file. – Martijn Pieters Sep 13 '18 at 13:17

2 Answers2

2

You could use the code you wrote but adjust the following:

with open('testrev.txt', 'w') as f:
    for line in lines:
        rev_line = reversed(line.split())
        f.write(" ".join(rev_line) + "\n")

This reverses the order of the words in each line while keeping the order of the lines.

GoTN
  • 135
  • 7
0

just making up the code you have written:

lines = []
with open('test.txt', "r") as f:
    lines = f.readlines()

with open('testrev.txt', 'w') as f:
    for line in lines:
        f.write(" ".join(reversed(line.split()))+"\n")

if you are using Python 3, the last line could look also like this:

        f.write(*reversed(line.split())+"\n")
Michal
  • 90
  • 1
  • 2
  • 5