简体   繁体   English

从文本文件中读取行,反向并保存在新的文本文件中

[英]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: 它执行以下操作:

  1. Split your string by line breaks - \\n , 按换行符拆分字符串 - \\n
  2. resulting an array 产生一个array
  3. reverses the array 反转阵列
  4. merges the array back with linebreaks \\n to a string 将数组与换行符\\n合并为一个string

Here the states: 这里的州:

  1. string: line1 \\n line2 \\n line3 string: line1 \\n line2 \\n line3
  2. array: ["line1", "line2", "line3"] 数组: ["line1", "line2", "line3"]
  3. array: ["line3", "line2", "line1"] 数组: ["line3", "line2", "line1"]
  4. string: 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: 如果您的输入文件太大而无法放入内存,这是一种有效的方法来反转它:

  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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从文本文件中读取行,反转句子并保存在新的文本文件中 - Read lines from a text file, reverse the sentence and save in a new text file 无法从控制台捕获新行并将其保存到文本文件中 - Unable to capture new lines from a console and save them into a text file 如何读取CSV或文本文件的行,循环遍历每行并保存为每行读取的新文件 - How To Read Lines of CSV or Text File, Loop Over Each Line and Save To a New File For Each Line Read 将文本文件中的行读入变量 - Read lines from a text file into variables python - 从特定文本行读取文件 - python - Read file from and to specific lines of text 读取文本文件中的多行 - Read multiple lines in a text file 在文本文件中的行之间读取 - Read between lines in text file 从名为“file1.txt”的文本文件中读取前两行 将从“file1.txt”中读取的两行写入新文件“file2.txt” - Read the first two lines from a text file named "file1.txt" Write the two lines read from "file1.txt" to a new file "file2.txt" 如何编写 python 从名为“file1.txt”的文本文件中读取前两行 将从“file1.txt”读取的两行写入新文件“file2.txt” - How write python to Read the first two lines from a text file named "file1.txt" Write the two lines read from "file1.txt" to a new file "file2.txt" 从文本文件中一次读取4行或几行 - to read from a text file 4 lines or several lines at a time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM