我正在尝试在读取 csv 文件时编写一个这样的 if 语句:
if row = [] or EOF:
do stuff
我在网上搜索过,但找不到任何方法可以做到这一点。帮忙?
最佳答案
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
以上就足够了。
要检查是否位于文件末尾,您还可以执行以下操作:
import os
with open(fname, 'rb') as f:
is_end = f.tell() == os.fstat(f.fileno()).st_size
但我认为你不需要。
关于Python 检测 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25510222/