StudentOIST
StudentOIST

Reputation: 189

Write python dictionary into textfile

I want to write my python dictionary in a text file where each line contain one key and its value, with comma as separation. I am using the following code:

with open(compounds, 'w') as f:
    for key, value in dict_NTID_IDs_in_EisDatabase.items():
        f.write('%s:%s\n' % (key, value))

But it returns me the following error TypeError: expected str, bytes or os.PathLike object, not list

Upvotes: 0

Views: 287

Answers (3)

Joaquim Ferrer
Joaquim Ferrer

Reputation: 613

The problem is that compounds, where you initialize it, cannot be interpreted as a file path because it's a list. Put this before that code:

compounds = "my_dict.txt"

This will write your dictionary in a file in the directory you're in. You can check the directory you're in, or change it with the os package.

Upvotes: 1

nsaura
nsaura

Reputation: 331

It should work with this :

with open(compounds, 'w') as f:
    for key, value in zip(dict_NTID_IDs_in_EisDatabase.keys(), dict_NTID_IDs_in_EisDatabase.values()):
        f.write('%s,%s\n' % (key, value))

You can also use dict.items() as you mentionned but dict.items() returns a tuple ((key0, value0), (key1, value1) ...).

To get back to your question, you can use :

with open(compounds, 'w') as f:
    for item in dict_NTID_IDs_in_EisDatabase.items():
        f.write('%s,%s\n' % (item[0], item[1]))

Upvotes: 0

vikas balyan
vikas balyan

Reputation: 806

I hope it will help you!

dic = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("dic.txt","w")
f.write( str(dic) )
f.close()

Upvotes: 0

Related Questions