#!/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 Answer
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()
3 Comments
supermitch
@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.Remi Guan
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() :Psupermitch
Oh right, I understand. Maybe I could edit my answer to be more complete by including that option...
line1 = f.readline()(notf.readlines())