Engy El-kafrawy
Engy El-kafrawy

Reputation: 68

python write to file from dictionary

I'm new with Python and I know that piece of code is very simple and lacks some statements, actually I need to write to file from dictionary. This code runs but only writes the last item in dict to the file which is "heba6677..." . Thanks for your help.

ab={'engy':'011199887765',
    'wafa2':'87878857578',
    'heba':'6677553636'}
for name, mobile in ab.items():
    print ('Contact %s at %s' % (name, mobile))
    f=open('D:\glo.txt','w')
    f.write(name)
    f.write(mobile)
f.close()

Upvotes: 3

Views: 15281

Answers (2)

Lev Levitsky
Lev Levitsky

Reputation: 65791

Each time you open the file in w mode, its previous content is erased. So you only should do it once, before the loop. Best of all, do it with a with statement:

ab={'engy':'011199887765',
    'wafa2':'87878857578',
    'heba':'6677553636'}
with open('D:\glo.txt','w') as f:
    for name, mobile in ab.items():
        print ('Contact %s at %s' % (name, mobile))
        f.write(name)
        f.write(mobile)

Upvotes: 2

Pierre GM
Pierre GM

Reputation: 20339

If you want to keep adding lines to your file, open it with the a mode, as described in the documentation:

for (name, mobile) in ab.iteritems():
    with open(...., "a") as f:
        print ('Contact %s at %s' % (name, mobile))
        f.write(name)
        f.write(mobile)

Using w as mode means writing: your file will be overwritten.

Upvotes: 7

Related Questions