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)

  

相关文章:

  • 2021-06-01
  • 2022-12-23
  • 2021-05-27
  • 2021-10-29
  • 2021-09-29
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-26
  • 2021-10-02
  • 2022-12-23
相关资源
相似解决方案