Python Read From File, Write in Reversed Order -


i'm doing exercise book, , can't figure out; isn't homework, i'm trying teach myself, , have been trying can think of make work!

i need read lines text file, , write lines new file, in reversed order.

my problem is, can reversed order (i'm assuming means last line of 'r' file printed first in 'w' file), prints words reversed, making unreadable.

is there way possibly write lines in reversed order, lines stay readable?

here's have:

filetoread = 'yolo.txt' file = open(filetoread, 'r') words = file.read() wrf = 'yip.txt' wfile = open(wrf, 'w')   lines in reversed(list(words)):     print wfile.write(lines) 

you may want note it's easier , safer use with statement. way don't have worry opening file , forgetting close it. plus, if exception occurs inside with block, file still closed automatically; you'd have use try...finally statement without with.

here's example using with:

with open('yolo.txt', 'r') readf, open('yip.txt', 'w') writef:     line in reversed(readf.readlines()):         writef.write(line) 

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -