Inserting each row from csv/txt into a new variable in Python

Viewed 25

I am new into programming. I am seeking help with inserting each row from csv/txt into a new variable in Python.

I have a CSV or TXT file (whichever is simpler to solve this problem) filled with say with IP addresses:

#lines.csv

192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7

I need to read this file and insert each row into a new variable (or into 1 dimensional table). For now I have a working code that reads each row.

import csv

with open("lines.csv") as csvFile:   #opens
  csvDATA = csv.reader(csvFile, delimiter=',')  #reads
  for row in csvDATA:   #loops
    print (row)   #prints
csvFile.close()

In another loop later, i will be cURLing each IP address, so if you think there is an easier way to approach this, please share it with me.

Any and all help will be appreciated! Thanks.

1 Answers

If I understand correctly, you can use csv.DictReader to return each row of the .csv as an ordered dict and then use zip() to map its values with the list of the URLs.

Try this :

import csv
from pprint import pprint

dict_of_ips = {}
with open("lines.csv", "r",  delimiter=',', encoding="utf-8-sig") as f:
    csvDATA = csv.DictReader(f, fieldnames=['IP address'])
    for row in csvDATA:
        dict_of_ips[row['IP address']] = ''

list_of_urls = ['url1', 'url2', 'url3', 'url4', 'url5', 'url6', 'url7']
out = dict(zip(dict_of_ips, list_of_urls))

pprint(out)
{'192.168.1.1': 'url1',
 '192.168.1.2': 'url2',
 '192.168.1.3': 'url3',
 '192.168.1.4': 'url4',
 '192.168.1.5': 'url5',
 '192.168.1.6': 'url6',
 '192.168.1.7': 'url7'}

pprint(out['192.168.1.1'])
'url1'
Related