简体   繁体   中英

write multiple lists in each line to txt file

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,...]

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

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM