3

I have tried searching, but I havent found exactly what I need. I am using python 3, and I need help writing a text file in reverse order to a different output file.

So this would be the input file

Hey, I am Fred
Fred, what's up
Fred fred fred

And this would be the output file

Fred fred fred
Fred, what's up
Hey, I am Fred

If anyone has any insight into how to accomplish I would really appreciate it,

alex
492k205 gold badges889 silver badges990 bronze badges
asked Nov 4, 2012 at 9:23

1 Answer 1

2
with open (input_file_name) as fi, open(output_file_name, 'w') as fo:
 fo.writelines(reversed(fi.readlines()))

If input_file is malformed (last line doesn't end with '\n') you may use a quick (maybe not too efficient) hack:

with open ('c:\\temp\\input_file') as fi, open('c:\\temp\\output_file', 'w') as fo:
 fo.write('\n'.join(reversed(fi.read().splitlines())))
answered Nov 4, 2012 at 9:41
4
  • Having a 't' flag when opening helps clarifying that it's text you get. Otherwise good. Commented Nov 4, 2012 at 9:58
  • Hey, this code almost works, but is doing something strange. Lets say the lines of the code are 1, new line 2, new line 3. The output file will contain 32, newline 1 The same goes for if the lines of code are say Fred, new line Tiger, new line Ant. The output file will contain AntTiger, newline Fred Commented Nov 4, 2012 at 22:45
  • @user1797763, there's nothing strange, it's a simple, not foolproof solution that doesn't handle malformed text files. Updated the answer for your case. Commented Nov 5, 2012 at 4:48
  • Perfect. Thanks, appreciate it. Commented Nov 5, 2012 at 20:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.