如何在没有括号的情况下将列表元素写入文本文件

时间:2020-11-12 15:01:00

标签: python list csv text-files writer

我有许多列表需要连接起来并打印到带有标题的文本文件中。我在下面的代码中简化了问题。在输出文本文件中,我想要的是每个标题下方都有一个数字,我希望能够编写串联列表,但是当我执行此操作时,文本文件将显示带有括号和逗号的列表。

代码

import csv

headers = ["emplyee ID","age","number of fish", "number of eyes","tentacles","spots"]
listA = [1102,33,17]
listB = [3,8,19]
output_list = listA + listB

results_filename = "my_results.txt"
filepath = ("/path/to/results/folder/")
results_file_path = filepath + results_filename
with open(results_file_path, 'w', newline='') as filey: 
    csv_writer = csv.writer(filey, delimiter = '\t', lineterminator='\r\n')
    csv_writer.writerow(["emplyee ID", "age", "number of fish", "number of eyes", "tentacles", "spots"])
filey.close()                                                                                                                                                                
      
                
with open(results_file_path, 'a', newline='') as filey: ## Python 3... with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    csv_writer = csv.writer(filey, delimiter = '\t', lineterminator='\r\n')
    #csv_writer.writerow([output_list])
    csv_writer.writerow([output_list[:]])   

输出

enter image description here 所需的输出

要写入文本文件的列表内容,以免出现逗号和括号,并且可以使用“传递”选项卡进行读取。

1 个答案:

答案 0 :(得分:1)

writerow can write any iterable of integers

对于Writer对象,行必须是字符串或数字的可迭代项

...因此您可以直接编写列表:

csv_writer.writerow(output_list)