当前位置: 动力学知识库 > 问答 > 编程问答 >

Python Read From File, Write in Reversed Order

问题描述:

I'm doing an exercise from a book, and can't figure this out; this isn't homework, I'm trying to teach myself, and I have been trying anything that I can think of to make this work!

I need to read lines from a text file, and then write the lines into a new file, in reversed order.

My problem is, I can get it into reversed order (I'm assuming that it means last line of the 'r' file is printed first in the 'w' file), but it also prints the words reversed, making it unreadable.

Is there a way to possibly write the lines in reversed order, but the lines stay readable?

Here's what I have:

filetoread = 'yolo.txt'

file = open(filetoread, 'r')

words = file.read()

wrf = 'yip.txt'

wfile = open(wrf, 'w')

for lines in reversed(list(words)):

print wfile.write(lines)

网友答案:

You may want to note that it's usually easier and safer to use the with statement. That way you don't have to worry about opening a file and forgetting to close it. Plus, if an exception occurs inside the with block, the file is still closed automatically; you'd have to use a try...finally statement to do this without with.

Here's your example using with:

with open('yolo.txt', 'r') as readf, open('yip.txt', 'w') as writef:
    for line in reversed(readf.readlines()):
        writef.write(line)
网友答案:

you mean something like

wfile.write("".join(reversed(list(open("some_file.txt")))))
分享给朋友:
您可能感兴趣的文章:
随机阅读: