我在Excel中使用宏来创建键/值对,如下所示:
Sub GetKeyValue()
Dim FileName As String, i As Integer, str As String
FileName = "C:\keyvalue.txt"
Open FileName For Output As #1
For i = 1 To 50
str = Cells(i, 1) & ", " & Cells(i, 2)
Print #1, str
Next i
Close #1
End Sub
以上采用A1-A50和B1-B50中的值,并将它们用作创建文件的基础。
我怎样才能在Python中做类似的事情?
我的想法是有两个文本文件,一个用于键,一个用于值,并将两者合并,然后将其存储在字典对象中。
答案 0 :(得分:1)
您可以使用csv模块,假设值和键来自同一文件的单元格A和B.
import csv
with open("file.csv", "r") as f:
reader = csv.reader(f)
d = {line[0]:line[1] for line in reader}
如果键和值来自不同的文件,您可以将这些对存储在字典中:
with open("keys.csv", "r") as the_keys, open("values.csv", "r") as the_values:
keys = csv.reader(the_keys)
values = csv.reader(the_values)
my_dic = {line1[0]:line2[0] for line1,line2 in zip(keys,values)}
# Write to a new csv file.
with open("final.csv", "wb") as out:
writer = csv.writer(out, delimiter=',')
for k,v in my_dic.iteritems():
writer.writerow([k,v])
您可以跳过csv模块,只需将文件写为:
with open("keys.txt", "r") as f, open("values.txt", "r") as x:
h = {line1.strip():line2.strip() for line1,line2 in zip(f,x)}
with open("final.csv", "w") as out:
for k,v in h.iteritems():
out.write("{},{}\n".format(k,v))