echo "hello world!"

python读文件判断是否已到EOF

python读文件判断是否已到EOF,也即结尾,一般其它语言都是以EOF直接来判断的,比如 if ( fp.read(chunk_size) == EOF),

但python到结尾后是返回空字符串的,所以python可以这样判断:

fp = open('path/to/file', 'r', encoding='utf-8')
str = ''
try:
    while True:
        s = fp.read(10)
        if s == '':
            break
        str += s
finally:
    fp.close()

print(str)

 

或用with 代替 try

str = ''
with open('readme.txt', 'r', encoding='utf-8') as fp:
    while True:
        s = fp.read(10)
        if s == '':
            break
        str += s
print(str)

  

posted @ 2018-09-17 15:13  又起风了~  阅读(16393)  评论(1编辑  收藏  举报
哈哈哈