如何在没有括号的情况下将列表元素写入文本文件
How to write list elements to a text file without the brackets
我有很多列表,我需要将它们连接起来并打印到带有 header 的文本文件中。我在下面的代码中简化了问题。我在输出文本文件中想要的是每个 header 下面都有一个数字,我希望能够编写连接列表,但是当我这样做时,文本文件显示带有括号和逗号的列表)。
代码
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[:]])
输出
期望的输出
要写入文本文件的列表内容,因此不存在逗号和括号,可以使用选项卡传送读取。
writerow
can write any iterable of integers:
A row must be an iterable of strings or numbers for Writer
objects
...所以可以直接写列表:
csv_writer.writerow(output_list)
我有很多列表,我需要将它们连接起来并打印到带有 header 的文本文件中。我在下面的代码中简化了问题。我在输出文本文件中想要的是每个 header 下面都有一个数字,我希望能够编写连接列表,但是当我这样做时,文本文件显示带有括号和逗号的列表)。
代码
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[:]])
输出
要写入文本文件的列表内容,因此不存在逗号和括号,可以使用选项卡传送读取。
writerow
can write any iterable of integers:
A row must be an iterable of strings or numbers for
Writer
objects
...所以可以直接写列表:
csv_writer.writerow(output_list)