簡體   English   中英

重新排序文本文件-Python

[英]Re-ordering text file - Python

我必須重新排序輸入文件,然后將輸出打印到新文件。

這是輸入文件:

 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
ifile_name = "hello/input.txt"
ofile_name = "hello/output.txt"
ifile_name = open(ifile_name, 'r')
lines = ifile_name.readlines()
ofile_name = open(ofile_name, "w")

lines[-1] = lines[-1].rstrip() + '\n'
start = 0
end = len(lines) - 1
while start < end:
    ofile_name.write(lines[start])
    ofile_name.write(lines[end])
    start += 1
    end -= 1
if start == end:
    ofile_name.write(lines[start])
ifile_name.close()
ofile_name.close()

使用兩個樞軸startend指向要寫入文件的哪一行。 一旦start == end ,將中間行寫入文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM