制作一个没有复杂的反转文件

时间:2014-11-05 04:53:42

标签: file python-3.x reverse os.path

我试图取一个文件,将其反转,并将其保存到另一个文件中。但是,我遇到了一个问题。

如果我反过来,例如:

The woods are lovely, dark and deep.
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.

我应该最终得到这个:

And miles to go before I sleep.
And miles to go before I sleep,
But I have promises to keep,
The woods are lovely, dark and deep.

然而,我最终得到的是:

And miles to go before I sleep.And miles to go before I sleep,
But I have promises to keep,
The woods are lovely, dark and deep.

这是我的代码,目前:

import os.path

endofprogram = False
try:
    fileName = input("Enter the name of the input file: ")
    print("\n")    
    infile = open(fileName, 'r')

    outfileName = input("Enter the name of the output file: ")
    print("\n")
    while os.path.isfile(outfileName):
        outfileName = input("File Exists. Enter name again: ")
        print("\n")        
    outfile = open(outfileName, 'w')
except IOError:
    print("Error opening file - End of program")
    endofprogram = True

if endofprogram == False:
    lines = infile.readlines()
    for reverse in lines[::-1]:
        print(reverse)
        outfile.write(reverse)

outfile.close()
infile.close()

为什么会发生这种情况,我该如何解决?谢谢。

1 个答案:

答案 0 :(得分:1)

看起来输入文件的最后一行不以换行符结尾。有很多方法可以解决这个问题;这是一个:

for reverse in lines[::-1]:
    if reverse[-1] != "\n":
        reverse += "\n"
    #etc