0
#!/usr/bin/python
import sys

def main():

    f=open("a",'r')
    line1=f.readlines()
    f.close()

    try:
        sys.stdout.write(line1)
    except:
        print "?"
if __name__ == "__main__":
    main()
1
  • You are trying to write a list to an open file descriptor. You need to write a string. I think what you're after is line1 = f.readline() (not f.readlines()) Commented Oct 18, 2015 at 23:51

1 Answer 1

1

f.readlines() doesn't return a single string, it returns a list of lines. Even if there's only one line! So sys.stdout.write() doesn't know how to handle that. If you iterate over that list of lines, and try to write each one, it works just fine:

#!/usr/bin/python
import sys

def main():

    f = open("a",'r')
    lines = f.readlines()  # lines is actually a list
    f.close()

    print lines  # You'll see your issue, here!
    try:
        for line in lines:
            sys.stdout.write(line)  # Works now
    except:
        print "?"

if __name__ == "__main__":
    main()
Sign up to request clarification or add additional context in comments.

3 Comments

@KevinGuan the best option in fact, if you can, is to simply use for line in f: without even needing to specify. The file object itself is an iterator that will return the lines one by one. Also note that f.read() just reads the entire file as one chunk, but readlines() splits the lines into a list. So they do different things, depending on what functionality you want.
Yes I know that, I think if OP just want to print the file out, however f.read() or for line in f: is simpler than f.readlines() :P
Oh right, I understand. Maybe I could edit my answer to be more complete by including that option...

Your Answer

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.