Python 从文本文件中读取行,反转并保存在新的文本文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19753814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read lines from a text file, reverse and save in a new text file
提问by JaAnTr
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?
我怎样才能做到这一点?
采纳答案by bitoffdev
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()
回答by fjarri
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')
):
read()
在单个字符串中返回整个文件。这就是为什么当你反转它时,它也会反转线条本身,而不仅仅是它们的顺序。您只想反转行的顺序,您需要使用readlines()
来获取它们的列表(作为第一个近似值,它相当于s = f.read().split('\n')
):
s = f.readlines()
...
f.writelines(s[::-1])
# or f.writelines(reversed(s))
回答by aIKid
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!
希望这可以帮助!
回答by Langusten Gustel
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:
它执行以下操作:
- Split your string by line breaks -
\n
, - resulting an
array
- reverses the array
- merges the array back with linebreaks
\n
to astring
- 通过换行符拆分您的字符串 -
\n
, - 结果是
array
- 反转数组
- 将带有换行符的数组合并
\n
到一个string
Here the states:
这里的状态:
- string:
line1 \n line2 \n line3
- array:
["line1", "line2", "line3"]
- array:
["line3", "line2", "line1"]
- string:
line3 \n line2 \n line1 \n
- 细绳:
line1 \n line2 \n line3
- 大批:
["line1", "line2", "line3"]
- 大批:
["line3", "line2", "line1"]
- 细绳:
line3 \n line2 \n line1 \n
回答by Saullo G. P. Castro
You can do something like:
您可以执行以下操作:
with open('test.txt') as f, open('output.txt', 'w') as fout:
fout.writelines(reversed(f.readlines()))
回答by Kobi K
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()
回答by ?smail Taha AYKA?
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()
回答by fallaciousreasoning
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. Secondly, we open our output file. Here we loop through the lines in reversed order, writing them to the output file as we go.
首先,我们初始化一个变量来保存我们的行。然后我们读取“test.txt”文件中的所有行。其次,我们打开我们的输出文件。在这里,我们以相反的顺序循环遍历这些行,边走边将它们写入输出文件。
回答by dux2
If your input file is too big to fit in memory, here is an efficient way to reverse it:
如果您的输入文件太大而无法放入内存,这里有一个有效的方法来反转它:
- Split input file into partial files (still in original order).
- 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)