首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从文件Python 3中倒转行

从文件Python 3中倒转行
EN

Stack Overflow用户
提问于 2014-11-04 00:22:30
回答 2查看 959关注 0票数 0

我正在尝试将Python 3中的文本文件中的行反转并写入到外部文件中。目前,我对不包含行尾\n的幼稚的最后一行有问题。我从这段代码中得到了一个TypeError。

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-04 21:44:28

最后我这么做是为了让它运转..。

代码语言:javascript
复制
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)  
票数 0
EN

Stack Overflow用户

发布于 2014-11-04 00:30:19

使用您的规范来完成这一任务的最简单的方法--假设我正确理解,并且您想要做的就是颠倒每一行的顺序--就是利用reverse方法来处理python中的列表。因此,对于任何给定的行:

代码语言:javascript
复制
#define line here
line_list = list(line)
line_list.reverse()
reversed_line = ''.join(line_list)

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

代码语言:javascript
复制
#define line here
line_list = list(line.replace('\n', ''))
line_list.reverse()
reversed_line = ''.join(line_list) + '\n'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26725722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档