I am trying to write a contacts program and I have to write some information to txt file. I create a list and two dictionaries
name = ['charles', 'frank', 'chris']
phonenumbers = {'charles' : '12345', 'frank' : '23456', 'chris' : '34567'}
emails = {'charles' : '[email protected]', 'frank' : '[email protected]', 'chris' : '[email protected]'}
and I have two variables
ld_names = names, phonenumbers, emails
files = ('name_file.txt', 'phonenumber_file.txt', 'emails.txt')
I want to get a result like this
name_file.txt
['charles', 'frank', 'chris']
phonenumber_file.txt
{'charles': '12345', 'frank': '23456', 'chris': '34567'}
emails.txt
{'charles': '[email protected]', 'frank': '[email protected]', 'chris': '[email protected]'}
as you can see i have 3 txt files. it's too verbose if I write them one by one. and I try to use for loop
for file in files:
for ld_name in ld_names:
print(ld_name)
print(file
this is the code i try to write to the files.
while True:
mes = input('please press your key:')
if mes == 'quit':
for file in files:
with open(file, 'ab') as f:
for ld_name in ld_names:
pickle.dump(ld_name, f)
f.close()
break
but the result is not I want to get
-
could you explain it more? i have no idea what are you trying to do! do you want them to write to a txt file?G.Jan– G.Jan2016年10月22日 05:55:08 +00:00Commented Oct 22, 2016 at 5:55
-
yes, i am trying to write a contact program and i need to write data of list & dicts to a file. as you can see i have 3 files and it's verbose if i try to write them one by onenear99– near992016年10月22日 06:45:41 +00:00Commented Oct 22, 2016 at 6:45
1 Answer 1
To dump json, you should use json instead of pickle. And if you are certain that the indexes of ld_names and files matches, then you can use enumerate with the files. Otherwise, I suggest using a dict of files (i.e {file: data, ...}). Try this sample code;
import json
if __name__ == '__main__':
names = ['charles', 'frank', 'chris']
phonenumbers = {'charles': '12345', 'frank': '23456', 'chris': '34567'}
emails = {'charles': '[email protected]', 'frank': '[email protected]', 'chris': '[email protected]'}
ld_names = names, phonenumbers, emails
files = ('name_file.txt', 'phonenumber_file.txt', 'emails.txt')
for i, file in enumerate(files):
with open(file, 'ab') as f:
json.dump(ld_names[i], f)
f.close()
pass
pass