为什么sys.stdout.write不能在python2中工作?

时间:2015-10-18 23:48:34

标签: python-2.7

#!/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 个答案:

答案 0 :(得分:1)

f.readlines()不会返回单个字符串,而是返回行列表。即使只有一条线!所以sys.stdout.write()不知道如何处理。如果你遍历那个行列表,并尝试编写每一行,它就可以正常工作:

#!/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()