Python检测EOF

2024-06-17 11:47:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在读取csv文件时,我试图编写一个if语句,该语句如下所示:

if row = [] or EOF:
    do stuff

我在网上搜索过,找不到任何办法。帮忙吗?在


Tags: or文件csvif语句dorowstuff
2条回答
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

以上就足够了。在

要检查您是否在文件末尾,您还可以执行以下操作:

^{pr2}$

但我认为你不需要。在

不确定我是否完全理解您,但是为了忽略空行,我将使用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

相关问题 更多 >