简体   繁体   中英

dict () - Python 2.7 From 3.5 -

Following my work on my prototype , I'm still trying to compare two CSV files. This time I use a dictionary.

My first file is something like:

IP
192.168.10.1
192.168.10.15
192.168.10.32

One single column, with IP addresses.

I want to check if these IP are also I another file called epoch.csv. If yes, I write a CSV file with the copy of the line in epoch.csv.

In Python 2.7, I wrote this code that works smoothly:

with open('IP.csv', 'r') as master:
    enum = csv.reader(master)
    master_indices = dict((r[0], i) for i, r in enumerate(enum))


with open('epoch.csv', 'r') as hosts:
    with open('result.csv', 'w') as results:
        reader = csv.reader(hosts)
        writer = csv.writer(results)

        for row in reader:
            index = master_indices.get(row[1])
            if index is not None:
                writer.writerow(row)

BUT, when I try to run this code with Python 3.5 (Windows), I get this error:

File "IP.py", line 43, in (module)
master_indices = dict((r[0], i) for i, r in enumerate(enum))
File "IP.py", line 43, in (genexpr)
master_indices = dict((r[0], i) for i, r in enumerate(enum))
IndexError: list index out of range

Why does it work in one case and not in the other one. I could of course reinstall 2.7 On all my machines, but I'd like to understand why it doesn't work...

EDIT :

So considering csv.DictReader, I guess I can modify this line :

with open('IP.csv', 'r') as master:
    enum = csv.reader(master)
    master_indices = dict((r[0], i) for i, r in enumerate(enum))

with something much simplier like this :

with open('IP.csv', 'r') as master:
    enum = csv.Dict.Reader(master)

Is it correct?

Is there any empty lines in IP.csv ?

Your code DID run "smoothly" in my computer under Python 3.5, but it will fail if I add a empty line to the start of the file.

Try to add print(enum) in your for loop and you will know what exactly lead to this exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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