[英]Inserting each row from csv/txt into a new variable in Python
I am new into programming.我是编程新手。 I am seeking help with inserting each row from csv/txt into a new variable in Python.我正在寻求帮助,将 csv/txt 中的每一行插入 Python 中的新变量中。
I have a CSV or TXT file (whichever is simpler to solve this problem) filled with say with IP addresses:我有一个 CSV 或 TXT 文件(以更简单的方式解决此问题),其中包含 IP 地址:
#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.稍后在另一个循环中,我将卷曲每个 IP 地址,所以如果您认为有更简单的方法来解决这个问题,请与我分享。
Any and all help will be appreciated.任何和所有的帮助将不胜感激。 Thanks.谢谢。
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.如果我理解正确,您可以使用csv.DictReader
将 .csv 的每一行作为有序 dict 返回,然后使用zip()
到 map 它的 URL 值。
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.