2015-11-17 54 views
1

我必须重新排序输入文件,然后将输出结果打印到新文件中。重新排序文本文件 - 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和堆栈溢出非常陌生。

在此先感谢。

回答

0
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,将中间行写入文件

1

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

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