[英]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? 我怎样才能做到这一点?
You can do something like: 你可以这样做:
with open('test.txt') as f, open('output.txt', 'w') as fout:
fout.writelines(reversed(f.readlines()))
read()
returns the whole file in a single string. read()
以单个字符串返回整个文件。 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')
): 你想只反转行的顺序,你需要使用readlines()
来获取它们的列表(作为第一个近似值,它相当于s = f.read().split('\\n')
):
s = f.readlines()
...
f.writelines(s[::-1])
# or f.writelines(reversed(s))
f = open("text.txt", "rb")
s = f.readlines()
f.close()
f = open("newtext.txt", "wb")
s.reverse()
for item in s:
print>>f, item
f.close()
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 执行此操作的代码如下
lines = []
with open('text.txt') as f:
lines = f.readlines()
with open('newtext.txt', 'w') as f:
for line in reversed(lines):
f.write(line)
Firstly, we initialize a variable to hold our lines. 首先,我们初始化一个变量来保存我们的行。 Then we read all the lines from the 'test.txt' file. 然后我们读取'test.txt'文件中的所有行。 Secondly, we open our output file. 其次,我们打开输出文件。 Here we loop through the lines in reversed order, writing them to the output file as we go. 在这里,我们以相反的顺序遍历行,将它们写入输出文件。
The method file.read()
returns a string of the whole file, not the lines. file.read()
方法返回整个文件的字符串,而不是行。
And since s
is a string of the whole file, you're reversing the letters, not the lines! 因为s
是整个文件的字符串,所以你要翻转字母而不是字母!
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! 希望这可以帮助!
Use it like this if your OS uses \\n
to break lines 如果您的操作系统使用\\n
打破行,请使用它
f = open("text.txt", "rb")
s = f.read()
f.close()
f = open("newtext.txt", "wb")
f.write(reversed(s.split("\n")).join("\n"))
f.close()
Main thing here is reversed(s.split("\\n")).join("\\n")
. 这里的主要内容是reversed(s.split("\\n")).join("\\n")
。
It does the following: 它执行以下操作:
\\n
, 按换行符拆分字符串 - \\n
, array
产生一个array
\\n
to a string
将数组与换行符\\n
合并为一个string
Here the states: 这里的州:
line1 \\n line2 \\n line3
string: line1 \\n line2 \\n line3
["line1", "line2", "line3"]
数组: ["line1", "line2", "line3"]
["line3", "line2", "line1"]
数组: ["line3", "line2", "line1"]
line3 \\n line2 \\n line1 \\n
string: line3 \\n line2 \\n line1 \\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. 一个使用列表的示例,因此它会更容易:我确定答案更优雅,但这种方式很清楚。
f = open(r"c:\test.txt", "rb")
s = f.read()
f.close()
rowList = []
for value in s:
rowList.append(value + "\n")
rowList.reverse()
f = open(r"c:\test.txt", "wb")
for value in rowList:
f.write(value)
f.close()
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()
If your input file is too big to fit in memory, here is an efficient way to reverse it: 如果您的输入文件太大而无法放入内存,这是一种有效的方法来反转它:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.