我对这个python编程很新。我有两个csv文件。我必须使用公共列名称合并它们。我一直在尝试通过查看其他几个帖子。但是无法在我的2.5版本的python中运行该代码。所以有人可以帮我解决这个问题。 文件可能如下所示
File1
split_name, vcc, temp, c
A, 1,2,1
B,2,3,5
File 2
split_name, cout, i, vout
A, 2.5,2, 1
B, 2.4,1,8
结果文件应该是这样的
split_name,vcc,temp,c,cout,i,vout
A, 1, 2, 1, 2.5,2,1
B, 2, 3, 5, 2.4,1,8
我尝试的代码是:
import csv
import array
import os
#def readfile2(file2name):
r = csv.reader(open('file1.csv','r'))
dict2 = {row[0]: row[1:] for row in r}
print str(dict2)
#print dict2.keys()
#def readfile1(file1name):
reader1 = csv.reader(open('file2.csv','r'))
for row in reader1:
dict1 = {row[0]: row[1:]}
#print str(dict1)
#print dict1.values()
print str(dict1)
keys = set(dict1.keys() + dict2.keys())
with open('output.csv', 'wb') as f:
w = csv.writer(f, delimiter=',')
w.writerows([[key, dict1.get(key, "''"), dict2.get(key, "''")] for key in keys])
但我遇到的错误是:
keys = set((dict1.keys())+(dict2.keys())) TypeError:+:'dict_keys'和'dict_keys'
不支持的操作数类型注意:我现在已经安装了python 3.4版本。
非常感谢您的帮助!
答案 0 :(得分:1)
首先,最好坚持使用特定版本的python。
您收到此错误
TypeError: unsupported operand type(s) for +: 'dict_keys' and 'dict_keys'
因为与Python 2.5不同,Python 3为key()
方法返回dictionary view。
你想从两个词组中得到键的联合。你可以这样说到python:
set(dict1.keys()) | set(dict2.keys())
其中|
运算符是两个集合的联合。
要解决你的任务应重写最后一行,以便writerows()
得到字符串列表作为参数,而不是列表列表。我认为使用for
循环而不是列表理解会更好。
以下是Python 3的代码,其中包含一些更改和注释:
import csv
reader1 = csv.reader(open('file1.csv','r'))
titles1 = next(reader1) # First row is titles. So we parse it separetly
dict1 = {row[0]: row[1:] for row in reader1}
reader2 = csv.reader(open('file2.csv','r'))
titles2 = next(reader2)
dict2 = {} # If we skipt this and do nto change behaviour in cilce we
# will get only last row every time
for row in reader2:
dict2[row[0]] = row[1:]
keys = set(dict1.keys()) | set(dict2.keys())
with open('output.csv', 'w', newline='') as f: # For CVS it's beeter to use
# text mode, not binary.
w = csv.writer(f, delimiter=',')
w.writerow(titles1 + titles2)
for key in keys:
w.writerow([key, ] +
dict1.get(key, [''] * (len(titles1)-1)) +
dict2.get(key, [''] * (len(titles2)-1))
)
答案 1 :(得分:0)