Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python write to file from dictionary [duplicate]

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()
like image 930
Engy El-kafrawy Avatar asked Jul 07 '26 03:07

Engy El-kafrawy


2 Answers

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.

like image 133
Pierre GM Avatar answered Jul 08 '26 17:07

Pierre GM


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)
like image 31
Lev Levitsky Avatar answered Jul 08 '26 18:07

Lev Levitsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!