首页 > 解决方案 > 将文件的内容从下到上翻转,第一行除外

问题描述

我正在尝试将除第一行之外的行颠倒过来:例如:

Header
first 
second 
third

带有以下代码的输出是:

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)

标签: python

解决方案


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

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

推荐阅读