Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何逐行反转文件?_Python - Fatal编程技术网

Python 如何逐行反转文件?

Python 如何逐行反转文件?,python,Python,我想弄明白这一点已经有一段时间了,但我就是搞不懂 我想反转一个像这样的文件 Hello there My name is How are you 我的意思是,我想让它看起来像这样 there Hello is name My you are How 我试过了 lines = [] with open('test.txt', "r") as f: lines = f.readlines() with open('testrev.txt', 'w') as f: for li

我想弄明白这一点已经有一段时间了,但我就是搞不懂

我想反转一个像这样的文件

Hello there
My name is
How are you
我的意思是,我想让它看起来像这样

there Hello
is name My
you are How
我试过了

 lines = []
with open('test.txt', "r") as f:
    lines = f.readlines()

with open('testrev.txt', 'w') as f:
    for line in reversed(lines):
        f.write(line)
并加入

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

很抱歉,我无法理解这一点,我们将非常感谢您的帮助

您可以使用您编写的代码,但需要调整以下内容:

with open('testrev.txt', 'w') as f:
    for line in lines:
        rev_line = reversed(line.split())
        f.write(" ".join(rev_line) + "\n")

这将颠倒每行中单词的顺序,同时保持行的顺序。

只是组成您编写的代码:

lines = []
with open('test.txt', "r") as f:
    lines = f.readlines()

with open('testrev.txt', 'w') as f:
    for line in lines:
        f.write(" ".join(reversed(line.split()))+"\n")
如果您使用的是Python 3,那么最后一行也可能是这样的:

        f.write(*reversed(line.split())+"\n")

提示:不要同时读取和写入文件。用户可以读取其他输出文件,也可以读取、处理、重新打开和写入。副本讨论的是反转给定行的单词,而不是字母。Python中的简短版本是
“”。join(line.split()[::-1])+“\n”
@KlausD::它们从一个文件读取,然后写入另一个文件。