python readline()逐行读,怎么判断已到末尾?

直接readlines(),怕文件太大
(且含有'\n'的空行)

阅读 46.3k
5 个回答

两种方法:

1. for ... in ...

with open("file") as fh:
    for line in fh:
        print(line.strip())

2. while fh.readline():

with open("file") as fh:
    line = fh.readline()
    while line:
        print(line.strip())
        line = fh.readline()

最简洁优雅又高效的自然是第一种, 如果题主非要用readline(), 则可以使用第二种, while循环, 读到最后一行没有内容会退出循环, 中间有空行不要紧, 空行不等于结尾(\n != EOF)

for ... in ...:

with open('filename') as fp:
    for line in fp:
        # do something

with open('filename','r') as f:

while True:
    line=f.readline()
    if line:
        print (line)
    else:
        break
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏