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)