文件

时间:2015-05-11 13:50:24

标签: python list file

我想为我的脚本使用生成器,但我总是异常:

Traceback (most recent call last):
  File "scan.py", line 56, in scan_m
    for line in ip_list:
  File "scan", line 46, in expand_ip_addr
    yield str(ip) + '\n'
UnboundLocalError: local variable 'ip' referenced before assignment

这是我的代码,我应该改变什么?我之前从未使用过发电机。

def expand_ip_addr():
    with open('ip.txt', 'r') as file_in:
            #remove blank lines
        for line in file_in:

            if '/' in str(line):
                for ip in IPNetwork(str(line)):
                    yield str(ip
            else:
                line

def scan_m(ip_list):
    i = 1
    try:
        for line in ip_list:
            # do something with the line
            i = i + 1


def main():
    ip_list = expand_ip_addr()
    scan_m(ip_list)

if __name__ == "__main__":
    main()

更新我的错误,其他声明错了,sry

1 个答案:

答案 0 :(得分:2)

更改

for line in file_in.read().replace('\n\n', '\n'):

else:
    yield str(ip) + '\n'

for line in file_in:
    line = line.strip()
    if not line: continue

else:
    yield line + '\n'