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

2020-06-21 07:03发布

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?

9条回答
放我归山
2楼-- · 2020-06-21 07:59

If your input file is too big to fit in memory, here is an efficient way to reverse it:

  1. Split input file into partial files (still in original order).
  2. Read each partial file from last to first, reverse it and append to output file.

Implementation:

import os
from itertools import islice

input_path = "mylog.txt"
output_path = input_path + ".rev"

with open(input_path) as fi:
    for i, sli in enumerate(iter(lambda: list(islice(fi, 100000)), []), 1):
        with open(f"{output_path}.{i:05}", "w") as fo:
            fo.writelines(sli)

with open(output_path, "w") as fo:
    for file_index in range(i, 0, -1):
        path = f"{output_path}.{file_index:05}"
        with open(path) as fi:
            lines = fi.readlines()
        os.remove(path)
        for line in reversed(lines):
            fo.write(line)
查看更多
The star\"
3楼-- · 2020-06-21 08:03

The method file.read() returns a string of the whole file, not the lines.

And since s is a string of the whole file, you're reversing the letters, not the lines!

First, you'll have to split it to lines:

s = f.read()
lines = s.split('\n')

Or:

lines = f.readlines()

And your method, it is already correct:

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

Hope this helps!

查看更多
再贱就再见
4楼-- · 2020-06-21 08:03

You have to work line by line.

f = open("text.txt", "rb")
s = f.read()
f.close()
f = open("newtext.txt", "wb")
lines = s.split('\n')
f.write('\n'.join(lines[::-1]))
f.close()
查看更多
登录 后发表回答