python 3.x - Making a reversed file without complications -
i attempting take file, reverse it, , save file. however, i've come across problem.
if reverse this, example:
the woods lovely, dark , deep. have promises keep, , miles go before sleep, , miles go before sleep.
i should end this:
and miles go before sleep. , miles go before sleep, have promises keep, woods lovely, dark , deep.
however, end getting this:
and miles go before sleep.and miles go before sleep, have promises keep, woods lovely, dark , deep.
this code, @ moment:
import os.path endofprogram = false try: filename = input("enter name of input file: ") print("\n") infile = open(filename, 'r') outfilename = input("enter name of output file: ") print("\n") while os.path.isfile(outfilename): outfilename = input("file exists. come in name again: ") print("\n") outfile = open(outfilename, 'w') except ioerror: print("error opening file - end of program") endofprogram = true if endofprogram == false: lines = infile.readlines() reverse in lines[::-1]: print(reverse) outfile.write(reverse) outfile.close() infile.close()
why happening , how can prepare it? give thanks you.
it looks lastly line of input file doesn't end in newline. there's number of ways deal that; here's one:
for reverse in lines[::-1]: if reverse[-1] != "\n": reverse += "\n" #etc
file python-3.x reverse os.path
No comments:
Post a Comment