[英]Writing csv in rows and columns
I am so close to being done but cant get my head around this problem. 我是如此接近完成,但是无法解决这个问题。 I am writing to csv and my code keeps giving me this output.
我正在写csv,我的代码不断给我这个输出。
dict,a,b,c,d
,,,,
list,1,2,3,4
I want it to be as follows: 我希望它如下:
dict, list
a,1
b,2
c,3
d,4
The code is: 代码是:
##Opening my dictionary .cvs file
with open('some_file.csv', mode='r') as infile:
reader = csv.reader(infile,)
DICT = {rows[0]:rows[1] for rows in reader if len(rows) == 2}
##Opening my enquiry list .cvs file
datafile = open(self.filename, 'r')
datareader = csv.reader(datafile)
n1 = []
for row in datareader:
n1.append(row)
n = list(itertools.chain(*n1))
headings = ['dict', 'list']
##Writing to .cvs file
with open(asksaveasfilename(), 'w') as fp:
a = csv.writer(fp)
# write row of header names
a.writerow(n)
# build up a list of the values in DICT corresponding to the keys in n
values = []
for name in n:
if name in DICT:
values.append(DICT[name])
else:
values.append("Not Available")
# now write them out
a.writerow(values)
I tried using writerows
but this prints the data wrong also 我尝试使用
writerows
但这也会打印错误的数据
d,i,c,t
a
b
c
d
l,i,s,t
1
2
3
4
SOLUTION: 解:
for nameValueTuple in zip(n,values):
a.writerow(nameValueTuple)
Did the trick 绝招
import csv
DICT = {a:a*a for a in [1,2,3,4,5]}
n = [2, 5, 99, 3]
headings = ['dict', 'list']
##Writing to .cvs file
with open("try.csv", 'w') as fp:
a = csv.writer(fp)
a.writerow(headings)
for name in n:
if name in DICT:
a.writerow([name, DICT[name]])
else:
a.writerow([name, "Not Available"])
This will result in try.csv
containing: 这将导致
try.csv
包含:
dict,list
2,4
5,25
99,Not Available
3,9
You can also do the processing and write everything at once: 您还可以进行处理并立即编写所有内容:
import csv
DICT = {a:a*a for a in [1,2,3,4,5,6]}
ns = [2,3,99,5]
headings = ['dict', 'list']
ns_squared = [DICT[name] if name in DICT else "NOT_FOUND" for name in names]
print(ns_squared) #=> [4, 9, 'NOT_FOUND', 25]
rows = zip(ns,ns_squared)
with open("try.csv", 'w') as fp:
a = csv.writer(fp)
a.writerow(headings)
a.writerows(rows)
This will then result in: 这将导致:
dict,list
2,4
3,9
99,NOT_FOUND
5,25
If you have columns as lists, you can turn these into rows by using the zip()
builtin function. 如果您将列作为列表,则可以使用内置的
zip()
函数将其转换为行。 For example: 例如:
>>> column1 = ["value", 1, 2, 3, 4]
>>> column2 = ["square", 2, 4, 9, 16]
>>> zip(column1,column2)
[('value', 'square'), (1, 2), (2, 4), (3, 9), (4, 16)]
Its been long time since I done python, (I'm assuming variable 'values' is an array) 自从我完成python以来已经很长时间了(我假设变量'values'是一个数组)
I think your writerow should be something like; 我认为您的写行应该是这样的;
#not sure about the syntax, mate...
a.writerow([for x in values])
otherwise use bultiin function zip 否则使用bultiin函数zip
Hope this helps... 希望这可以帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.