簡體   English   中英

python中的CSV文件處理

[英]CSV file handling in python

我有以下格式的兩個csv文件:

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

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

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

1
3
2
4

我的目標是讀取第二個文件(text.csv)並將數字存儲在列表中。 然后,我想在第一個文件(data.csv)中找到與這些數字相對應的顏色。

因此,我的最終輸出應類似於:

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

我想考慮使用字典,但似乎無法理解我該怎么做。

使用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文件的順序相同)

這應該工作:

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

print D[1]
#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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM