Brian
Brian

Reputation: 115

Combine text files into key/value

I'm using a macro in Excel to create a key/value pair as follows:

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

The above takes the values in A1-A50 and B1-B50 and uses them as a basis for creating the file.

How could I do something similar in Python?

My thinking is having two text files, one for the keys and one for the values, and merging the two and then storing it in a dictionary object.

Upvotes: 0

Views: 878

Answers (1)

Daniel
Daniel

Reputation: 5391

You can use the csv module assuming the values and keys come from cell A and B of the same file.

import csv
with open("file.csv", "r") as f:
    reader = csv.reader(f)
    d = {line[0]:line[1] for line in reader}

If the keys and values come from different files you can store the pairs in a dictionary as:

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])

You can skip the csv module and just write the files as:

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))

Upvotes: 1

Related Questions