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)):
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
Here's your example using
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