簡體   English   中英

如何將兩個相互匹配的列表輸出到一個txt文件中

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

我這里有兩個列表:

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

我需要將這兩個列表輸出到這樣的 txt 文件中:

rate    date    population
4    2/3/2021    1523

兩個單詞之間的空格是一個制表符,我嘗試使用類似的代碼

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

但它不起作用,我不知道如何將選項卡空間選項放入其中。 需要一些幫助! 謝謝!

您可以使用csv模塊的DictWriter編寫制表符分隔的文件。 為此,您可以將分隔符指定為制表符。

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)

您可以嘗試使用\\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))

您可以使用下面的代碼段實現您的結果

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)

我會使用csv模塊:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM