从文件Python 3中反转行

时间:2014-11-04 00:22:30

标签: python file python-3.x reverse

我试图使Python 3中的文本文件中的行被反转并写入outfile。目前,我遇到的问题是infile的最后一行不包含\ n在行尾。我从这段代码得到一个TypeError。

def main():

    endofprogram = False
    try:
        inputfile = input("Enter name of input file: ")

        ifile = open(inputfile, "r", encoding="utf-8")

        outputfile = input("Enter name of output file: ")
        while os.path.isfile(outputfile):
            if True:
                outputfile = input("File Exists. Enter name again: ")        
        ofile = open(outputfile, "w")        


    except IOError:
        print("Error opening file - End of program")
        endofprogram = True

    #If there is not exception, start reading the input file

    if endofprogram == False:
        newline = "\n"
        for line in ifile:
            line = line.strip            
            line = line + "\n"            
            lines = ifile.readlines()

    lines.reverse()
    newlines= "".join(lines)
    print(newlines)     
    ifile.close()
    ofile.close()

main() # Call the main to execute the solution

2 个答案:

答案 0 :(得分:0)

使用您的规范执行此操作的最简单方法 - 假设我理解正确并且您想要做的只是颠倒每行的顺序 - 只是为了利用reverse方法在python中列出。所以,对于任何给定的行:

#define line here
line_list = list(line)
line_list.reverse()
reversed_line = ''.join(line_list)

编辑:根据您对换行符的问题,这里有一个修改:

#define line here
line_list = list(line.replace('\n', ''))
line_list.reverse()
reversed_line = ''.join(line_list) + '\n'

答案 1 :(得分:0)

我最终这样做是为了让它发挥作用......

if endofprogram == False:         

    lines = ifile.readlines()
    linelist = []
    for line in lines:
        line = line.strip("\n")
        line = line + "\n"

        linelist.append(line)


    linelist.reverse()

    newlines= "".join(linelist)
    ofile.write(newlines)