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
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
-
Having a 't' flag when opening helps clarifying that it's text you get. Otherwise good.Lennart Regebro– Lennart Regebro11/04/2012 09:58:16Commented 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 Fredpythonhack– pythonhack11/04/2012 22:45:28Commented 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.panda-34– panda-3411/05/2012 04:48:33Commented Nov 5, 2012 at 4:48
-
Perfect. Thanks, appreciate it.pythonhack– pythonhack11/05/2012 20:09:52Commented Nov 5, 2012 at 20:09
lang-py