3

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.