问题
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