Python detecting EOF

允我心安 提交于 2020-01-30 08:16:46

问题


I'm trying to write an if statement that goes as such, while reading a csv file:

if row = [] or EOF:
    do stuff

I've searched online and couldn't find any way of doing this. Help?


回答1:


with open(fname, 'rb') as f:
    for line in f:
        # line = line.strip(' \r\n') # to remove spaces and new line chars if needed
        if not line:
            do stuff
    do stuff

The above is sufficient.

To check if you are in the end of file you can also do:

import os
with open(fname, 'rb') as f:
   is_end = f.tell() == os.fstat(f.fileno()).st_size

but I think you do not need to.




回答2:


Not sure if I fully understand you but to ignore empty lines I would use if line.strip().

with open("in.txt") as f:
    for line in f:
        if line.strip():
            # append
        else:
            # do what you need
    # do last requirement


来源:https://stackoverflow.com/questions/25510222/python-detecting-eof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!