简体   繁体   English

读取结尾为空行的文件时出错

[英]error when reading a file with blank lines to the end

I'm trying to read a file line by line and do some stuff. 我正在尝试逐行读取文件并做一些事情。 The problem is that if I add a bunch of blank lines to the end of the file, I'm getting an exception (list index out of range). 问题是,如果我在文件末尾添加一堆空行,则会出现异常(列表索引超出范围)。

def check_ip(address):
  try:
    socket.inet_aton(address)
    return True
  except:
    return False

def myfunction:
    with open(filename, 'r') as f:
      for line in f.readlines():
        if not line: continue
        tokens = line.strip().split()
        if not check_ip( tokens[0]  ): continue
        // do some stuff

Your empty line test doesn't take into account whitespace. 空行测试不考虑空格。

Use: 采用:

if not line.strip(): continue

otherwise you end up with an empty tokens list for those lines. 否则,您最终将获得这些行的空tokens列表。

You don't have to call str.strip() when also using str.split() with no arguments; 你不必调用str.strip()时,也使用str.split()不带参数; that call already strips leading and trailing whitespace: 该调用已经去除了开头和结尾的空格:

tokens = line.split()

Note that you don't need (nor want) to use f.readlines() ; 请注意,您不需要(也不想要)使用f.readlines() you can iterate over the file object directly : 您可以直接遍历文件对象:

for line in f:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM