Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.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,除了第一行之外,我正在尝试将这些行颠倒过来: 例如: 以下代码的输出为: third second first Header 我想做的是: Header third second first 代码如下: with open('file.txt', 'r') as f: lines = f.readlines() with open('output.txt', 'w+') as f: for l in reversed(lines): f.write(l)

除了第一行之外,我正在尝试将这些行颠倒过来: 例如:

以下代码的输出为:

third
second
first
Header
我想做的是:

Header
third
second
first
代码如下:

with open('file.txt', 'r') as f:
    lines = f.readlines()

with open('output.txt', 'w+') as f:
    for l in reversed(lines):
        f.write(l)

这似乎是你想要的:

with open('file.txt', 'r') as f:
    lines = f.readlines()

firstline = lines[0] # get the first line from the file
lines.pop(0) # remove the first line from the lines list, since it's stored separately

with open('output.txt', 'w+') as f:
    f.write(firstline) # write the first line to the file
    for l in reversed(lines): # write the rest of the lines to the file
        f.write(l)
它在output.txt中输出:

Header
third
second 
first 

这似乎是你想要的:

with open('file.txt', 'r') as f:
    lines = f.readlines()

firstline = lines[0] # get the first line from the file
lines.pop(0) # remove the first line from the lines list, since it's stored separately

with open('output.txt', 'w+') as f:
    f.write(firstline) # write the first line to the file
    for l in reversed(lines): # write the rest of the lines to the file
        f.write(l)
它在output.txt中输出:

Header
third
second 
first 

谢谢你的帮助。