【问题标题】:error when reading a file with blank lines to the end读取带有空行到末尾的文件时出错
【发布时间】:2014-09-27 03:07:10
【问题描述】:

我正在尝试逐行读取文件并做一些事情。问题是,如果我在文件末尾添加一堆空行,我会得到一个异常(列表索引超出范围)。

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

【问题讨论】:

    标签: python sockets io


    【解决方案1】:

    您的空行测试没有考虑空格。

    用途:

    if not line.strip(): continue
    

    否则,这些行的 tokens 列表将是空的。

    在使用不带参数的str.split() 时,您不必调用str.strip();该调用已经去除了前导和尾随空格:

    tokens = line.split()
    

    请注意,您不需要(也不想)使用f.readlines();你可以迭代文件对象直接

    for line in f:
    

    【讨论】:

    • 您确定 split() 不需要 strip() 吗?看起来 '\n' 并没有被 split() 单独删除
    • @Bob: str.split() 不带参数,或将None 作为第一个参数,删除前导和尾随空格。所以是的,我确定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多