gpt4 book ai didi

python - 重新排序文本文件 - Python

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:43 24 4
gpt4 key购买 nike

我必须重新排序输入文件,然后将输出打印到新文件。

这是输入文件:

 The first line never changes.  
The second line was a bit much longer.
The third line was short.
The fourth line was nearly the longer line.
The fifth was tiny.
The sixth line is just one line more.
The seventh line was the last line of the original file.

输出文件应如下所示:

 The first line never changes.                                            
The seventh line was the last line of the original file.
The second line was a bit much longer.
The sixth line is just one line more.
The third line was short.
The fifth was tiny.
The fourth line was nearly the longer line.

我已经有代码可以反转输入文件并将其打印到输出文件,如下所示

ifile_name = open(ifile_name, 'r')
lines = ifile_name.readlines()
ofile_name = open(ofile_name, "w")

lines[-1] = lines[-1].rstrip() + '\n'
for line in reversed(lines):
ofile_name.write(line)
ifile_name.close()
ofile_name.close()

我是否可以在保留反向代码的同时在文本文件中获得所需的格式?

例如打印输入文件的第一行,然后反转并打印该行,打印输入文件的第二行,然后反转并打印该行等。

抱歉,如果这看起来不清楚,我对 Python 和堆栈溢出非常陌生。

提前致谢。

最佳答案

如果您不关心生成的列表,我相信这是一个非常优雅的解决方案。

with open("ifile_name","r") as f:
init_list=f.read().strip().splitlines()

with open("result.txt","a") as f1:
while True:
try:
f1.write(init_list.pop(0)+"\n")
f1.write(init_list.pop()+"\n")
except IndexError:
break

关于python - 重新排序文本文件 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33756099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com