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
谢谢你的帮助。