简体   繁体   中英

How to output two lists match to each other into a txt file

I have two lists here:

a=["rate","date","population"]
b=[4,2/3/2021,1523]

and I need to ouput these two lists into a txt file like this:

rate    date    population
4    2/3/2021    1523

the blank space between two words is a tab and I tried to use code like

with open("data.txt","w") as outfile:
zipped = zip(a, b)
set1=[]
for i, r in zipped:
    set1.append(i)
    set1.append(r)
 outfile.write(str(set1))

but it doesn't work and I don't know how to put the tab space choice into it. Need some helps! Thank you!

You can use csv module's DictWriter to write tab-delimited files. To do that, you can specify the delimiter as the tab character.

import csv
filename = "output.txt"
a = ["rate","date","population"]
b = [4,2/3/2021,1523]
values = dict(zip(a,b))

with open(filename, 'wb') as f:
    writer = csv.DictWriter(f, delimiter='\t', fieldnames=a)
    writer.writeheader()
    writer.writerows(values)

You can try using \\t :

a=["rate","date","population"]
b=["4","2/3/2021","1523"]

with open("data.txt","w") as outfile:
    outfile.write('\t'.join(a)+'\n')
    outfile.write('\t'.join(b))

you can achieve your result using snippet below

a=["rate","date","population"]
b=['4','2/3/2021','1523']

result = '\t'.join(a) + '\n' + '\t'.join(b)

with open('result.txt', 'w') as f:
    f.writelines(result)

I'd use the csv module:

import csv

with open("data.txt", "w") as outfile:
    writer = csv.writer(outfile, delimiter='\t')
    writer.writerow(a)
    writer.writerow(b)
a=["rate","date","population"] b=[4,"2/3/2021",1523] with open("data.txt","w") as outfile: for x in a: outfile.write(f'{x}\t') outfile.write('\n') for x in b: outfile.write(f'{x}\t') outfile.write('\n')

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