So far I have this code:
f = open("text.txt", "rb")
s = f.read()
f.close()
f = open("newtext.txt", "wb")
f.write(s[::-1])
f.close()
The text in the original file is:
This is Line 1
This is Line 2
This is Line 3
This is Line 4
And when it reverses it and saves it the new file looks like this:
4 eniL si sihT 3 eniL si sihT 2 eniL si sihT 1 eniL si sihT
When I want it to look like this:
This is line 4
This is line 3
This is line 2
This is line 1
How can I do this?
You can do something like:
read()
returns the whole file in a single string. That's why when you reverse it, it reverses the lines themselves too, not just their order. You want to reverse only the order of lines, you need to usereadlines()
to get a list of them (as a first approximation, it is equivalent tos = f.read().split('\n')
):A sample using list so it will be much easier: I'm sure there answer that are more elegant but this way is clear to understand.
There are a couple of steps here. First we want to get all the lines from the first file, and then we want to write them in reversed order to the new file. The code for doing this is as follows
Firstly, we initialize a variable to hold our lines. Then we read all the lines from the 'test.txt' file. Secondly, we open our output file. Here we loop through the lines in reversed order, writing them to the output file as we go.
Use it like this if your OS uses
\n
to break linesMain thing here is
reversed(s.split("\n")).join("\n")
.It does the following:
\n
,array
\n
to astring
Here the states:
line1 \n line2 \n line3
["line1", "line2", "line3"]
["line3", "line2", "line1"]
line3 \n line2 \n line1 \n