简体   繁体   English

Python:如何从 CSV 文件中读取键值对?

[英]Python : How to read Key Value pair from CSV file?

I have a csv file having 3 columns and I want to read 1st and 3rd column as key value pair.我有一个包含 3 列的 csv 文件,我想将第一列和第三列作为键值对读取。 I am doing it like below but it's not working.我正在像下面那样做,但它不起作用。

with open(dirName + fileName) as f:
       for line in f:
            (key, value) = line.split(',')

I'm thinking you want something like:我想你想要这样的东西:

with open(dirName + fileName) as f:
       for line in f:
            fields = line.split(',')
            assert len(fields) == 3
            (key, _, value) = fields

But maybe glance at the csv module.但也许看一眼 csv 模块。

Any time you're working with csv files use the csv module .任何时候处理 csv 文件时,都可以使用csv模块
As @Buckeye14Guy says: you should also use pathlib for path manipulations.正如@Buckeye14Guy 所说:您还应该使用pathlib进行路径操作。
And, for fast lookup, you can store key-value pairs in a dictionary, d .而且,为了快速查找,您可以将键值对存储在字典d

import csv, pathlib

d = {}
your_path = pathlib.PurePath(dirName).joinpath(filename)
with open(your_path,'r') as f:  
    reader = csv.reader(f) 
    for line in reader: 
        d[line[0]] = line[2] # dict entry with key = 1st col and value = 3rd col

Try this尝试这个

with open(file,'r+') as text:
 for line in text.readlines():
     (key, value) = line.split(',')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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