【问题标题】:CSV file handling in pythonpython中的CSV文件处理
【发布时间】:2016-02-24 05:03:33
【问题描述】:

我有两个格式如下的 csv 文件:

第一个文件(data.csv):-

1,红色 3、蓝色 4、绿色 2、灰色 5、黑色

第二个文件(text.csv):-

1 3 2 4

我的目标是读取第二个文件 (text.csv) 并将数字可能存储在一个列表中。然后我想在第一个文件(data.csv)中找到与这些数字对应的颜色。

因此,我的最终输出应该类似于:

1,红色 2、灰色 3、蓝色 4、绿色

我想考虑使用字典,但似乎不明白我会怎么做。

【问题讨论】:

  • 请发布你已经走了多远......
  • 这不像是我试图解决的硬件问题。我正在学习不同的 csv 概念,答案确实对我有帮助,我投票给了他们。

标签: python list csv dictionary


【解决方案1】:

这应该可行:

D = {}
with open('data.cvs') as f:
    for line in f:
        x, y = line.split(',')
        D[int(x)] = y

print D[1]

【讨论】:

  • AttributeError: 'dict' 对象没有属性 'split'
  • 我不这么认为...试试 agian :)
【解决方案2】:
#First populate the data dictionnary with data.csv file :
data = {}
with open('data.csv', 'r') as f:
    for line in f:
        try:
            index, value = line.split(',')
            data[index.replace('\r','').strip()] = value.replace('\r','').strip()
        except Exception as e:
            print('[!] Error hanling data line : %s - %s' % (line, e))

#Then compare the second file :
with open('text.csv', 'r') as f:
    for line in f:
        try :
            line = line.replace('\r','').strip()
            print('%s => %s' % (line, data[line]))
        except Exception as e:
            print('[!] Error finding %s in data - %s' % (line, e))

【讨论】:

    【解决方案3】:

    使用csv 模块可以为您省去一些麻烦;试试

    import csv
    import sys
    
    # version compatibility shim!
    if sys.hexversion < 0x3000000:
        # Python 2.x
        opencsv = lambda f: open(f, mode="rb")
    else:
        # Python 3.x
        opencsv = lambda f: open(f, newline="")
    
    # read color data to a dictionary
    with opencsv("data.csv") as inf:
        color = {int(num):col for num,col in csv.reader(inf)}
    
    # do translation
    with opencsv("text.csv") as inf:
        for num, in csv.reader(inf):
            num = int(num)
            print("{},{}".format(num, color[num]))
    

    产生

    1,red
    3,blue
    2,gray
    4,green
    

    (与 text.csv 文件的顺序相同)

    【讨论】:

    • +1 用于使用 csv 模块,所有其他方法都会导致该模块已经处理的各种问题
    猜你喜欢
    • 2013-04-22
    • 2019-01-17
    • 1970-01-01
    • 2023-04-06
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    相关资源
    最近更新 更多