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

Time:10-26

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!

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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)

edit: If you want to fix your code and not use the csv module:

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

The '\t'.join(a) is a useful function of str which will join together each value in a with a \t separating:

>>> '\t'.join(["if", "this", "isn't", "nice", "what", "is?"]
"if\tthis\tisn't\tnice\twhat\tis?"

>>> print(_)
if      this    isn't   nice    what    is?
  • Related