Copy and Reverse

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wocosc
    New Member
    • Mar 2007
    • 18

    #1

    Copy and Reverse

    So far, I have:

    from string import *
    def reverse():
    fname = raw_input("Ente r a Filename: ")
    infile = open(fname, 'r')
    data = infile.read()
    list(data)
    print fname[-1:1]



    I need python to read the file (whichever the user wants to open), but print it in reverse and save it. I know I need to treat the file as a string, but I am obviously not doing something right.. Any help would be great.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by wocosc
    So far, I have:

    from string import *
    def reverse():
    fname = raw_input("Ente r a Filename: ")
    infile = open(fname, 'r')
    data = infile.read()
    list(data)
    print fname[-1:1]



    I need python to read the file (whichever the user wants to open), but print it in reverse and save it. I know I need to treat the file as a string, but I am obviously not doing something right.. Any help would be great.
    Here's one way of doing it:
    Code:
    lineList = open('your_file').readlines()
    outStr = ''
    for line in lineList:
        s = list(line.strip())        # strip newline character and make list of characters
        s.reverse()                    # reverse character list in place
        outStr += '%s\n' % (''.join(s))        # create output string for writing

    Comment

    Working...