2
import os.path
try:
    file1=input("Enter input file: ")
    infile=open(filename1,"r")
    file2=input("Enter output file: ")
    while os.path.isfile(file2):
        file2=input("File Exists! Enter new name for output file: ")
    ofile=open(file2, "w")
    content=infile.read()
    newcontent=content.reverse()
    ofile.write(newcontent)    

except IOError:
    print("Error")

else:
    infile.close()
    ofile.close()

Am I on the right track with this code? I can't seem to find a method to reverse the lines in the input file for the output file.

Input ex.

cat dog house animal

plant rose tiger tree

zebra fall winter donkey

Output ex.

zebra fall winter donkey

plant rose tiger tree

cat dog house animal
lfhfsfhjsf
  • 63
  • 3
  • 7
  • `reverse()` is an _in-place_ operation - which means it won't return the reversed list, it will modify the list in-place that is, it will reverse the list, but won't return anything. In Python, any method that does not have an explicit return value returns `None`, so this line: `newcontent=content.reverse()` is going to reverse `content`, but set `newcontent` to `None`. – Burhan Khalid Nov 06 '13 at 04:30
  • You can read any file in reverse order, BUT, if your file is large this does not make sense ! – Siva Cn Nov 06 '13 at 04:40
  • @SivaCn: there is `tac` command in gnu coreutils that does exactly that. BSD `tail` command supports `-r` option. – jfs Nov 06 '13 at 06:09

2 Answers2

1

Loop through the lines, in a reversed order. Here is a couple of ways.

Using range:

lines = infile.readlines()
for i in range(len(l)-1,-1, -1):
     print l[i]

The slice notation:

for i in l[::-1]:
    print i

Or, just use the built-in reversed function:

lines = infile.readlines()
for i in reversed(lines):
    newcontent.append(i)
aIKid
  • 26,968
  • 4
  • 39
  • 65
0

This should work

import os.path
try:
  file1=raw_input("Enter input file: ") #raw input for python 2.X or input for python3 should work
  infile=open(file1,"r").readlines() #read file as list
  file2=raw_input("Enter output file: ")
  while os.path.isfile(file2):
    file2=raw_input("File Exists! Enter new name for output file: ")
  ofile=open(file2, "w")
  ofile.writelines(infile[::-1])#infile is a list, this will reverse it
  ofile.close()
except IOError:
  print("Error")
jwillis0720
  • 4,329
  • 8
  • 41
  • 74