1

I would like to write lines in a txt file with a multiple of input list.This is what I wrote to write line in my txt file:

for line in pg:
for key,value in line.items():
    if key == 'name':
        name.append(value)
    elif key == 'age':
        age.append(value)
    elif key == 'address':
        address.append(value)

with open('sampel.list',mode='w') as f:
                      f.write('name:{n},age:{a},address:{d}\n'.format(n=name,a=age,d=address))

The output that I want is:

name:paulina,age:19,address:NY
name:smith,age:15,address:AU
 .
 .
 .

But my output is

name:[paulina,smith,...],age:[19,15,...],address:[NY,AU,...]
  • It helps a bit more if you posted a bit more of the code, specifically how you defined your variables.. it looks like name, age and address are all lists – ewokx Jul 15 '20 at 02:10
  • You might want to loop at using `zip()`, which lets you iterate over multiple lists simultaneously. https://stackoverflow.com/questions/10080379/what-is-the-best-way-to-iterate-over-multiple-lists-at-once – shynjax287 Jul 15 '20 at 02:14
  • @ewong I already put the code on how I extract my data. – stack stack Jul 15 '20 at 02:14

2 Answers2

0

Given individual lists of values, you can use zip() to combine them and them loop over the result for each line:

name = ['Joe', 'Tom', 'Sally']
age = [10, 12, 14]
address = ['1 main st', '2 main st', '3 main st']

with open('sampel.list',mode='w') as f:
    for n, a, d in zip(name, age, address):
        f.write(f'name:{n},age:{a},address:{d}\n')

This will result in a file like:

name:Joe,age:10,address:1 main st
name:Tom,age:12,address:2 main st
name:Sally,age:14,address:3 main st
Mark
  • 90,562
  • 7
  • 108
  • 148
0

You need to iterate through your list and print values.

for line in pg:
for key,value in line.items():
    if key == 'name':
        name.append(value)
    elif key == 'age':
        age.append(value)
    elif key == 'address':
        address.append(value)

with open('sampel.list',mode='w') as f:
    for i in range(len(name)):
        f.write('name:{n},age:{a},address:{d}\n'.format(n=name[i],a=age[i],d=address[i]))