简体   繁体   English

将数字列表写入 Python 中的 CSV 文件

[英]Write list of numbers to CSV file in Python

I have a list of 4-digit numbers (1234, 1234, 1234) in Python that I would like to write to a CSV file.我在 Python 中有一个 4 位数字(1234、1234、1234)的列表,我想将其写入 CSV 文件。

I am using the csv library, this is the code I have:我正在使用 csv 库,这是我的代码:

with open('converted2.csv','w') as new_file:
 write=csv.writer(new_file)
 write.writerows(results)

However, when I import the values into a file, they are spread across rows但是,当我将值导入文件时,它们分布在各行中

How could I prevent this from happening and have the four-digit numbers all under one column only?我怎样才能防止这种情况发生并让四位数字只在一列下?

Thank you!谢谢!

use the lambda method provided inside writerows to print rows使用 writerows 中提供的 lambda 方法打印行

import csv

results = [1234, 1234, 1234]
with open('converted2.csv','w') as new_file:
 write=csv.writer(new_file)
 write.writerows(map(lambda x: [x], results))

$ cat converted2.csv 
1234
1234
1234

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM