Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read lines from a text file, reverse and save in a new text file

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?

like image 954
JaAnTr Avatar asked Nov 03 '13 14:11

JaAnTr


People also ask

How do you reverse a line in notepad?

Edit > Select All. TextFX > TextFX Tools > Insert Line Numbers. If TextFX > TextFX Tools > +Sort ascending is checked, uncheck it.

How do you read a reverse file?

Reading Words Backward We can also read the words in the file backward. For this we first read the lines backwards and then tokenize the words in it with applying reverse function. In the below example we have word tokens printed backwards form the same file using both the package and nltk module.


2 Answers

You can do something like:

with open('test.txt') as f,  open('output.txt', 'w') as fout:
    fout.writelines(reversed(f.readlines()))
like image 122
Saullo G. P. Castro Avatar answered Nov 02 '22 02:11

Saullo G. P. Castro


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 use readlines() to get a list of them (as a first approximation, it is equivalent to s = f.read().split('\n')):

s = f.readlines()
...
f.writelines(s[::-1])
# or f.writelines(reversed(s))
like image 4
fjarri Avatar answered Nov 02 '22 01:11

fjarri