Python:将清单清单写入CSV [英] Python: Write list of lists to CSV
问题描述
在我的python脚本中,我有一个具有以下结构的列表:
In my python script I'm having a list that has the following structure:
['00:00', 'abc', '2', 'xyz']
['00:01', 'cde', '3', 'sda']
,依此类推.我想将此列表写入csv文件,其方式是每个元素都在单独的行中,而一个元素中的每个字符串在单独的列中.所以我想在csv文件中得到以下结果:
and so on. I want to write this list to csv file in a way that every element is in separate row and every string in one element is in separate column. So I want to end up with the following result in csv file:
A | B | C | D
1 00:00 | abc | 2 | xyz
2 00:01 | xyz | 3 | sda
目前,我有这样的代码:
Currently I have a code like this:
with open('test1.csv',mode='w',encoding='UTF-8') as result_file:
wr = csv.writer(result_file, dialect='excel')
for x in data:
wr.writerow(x)
我得到的结果是列表中的每个元素都被写入了A列,所以看起来像这样:
and the result I get is that every element of the list is written to column A, so it looks like this:
A |
1 '00:00','abc','2','xyz' |
如何实现将每个字符串拆分为csv文件中的单独列?
How can I achieve splitting each string to separate column in csv file?
-编辑
如果我从前三个答案中运行代码,我将得到相同的结果(除定界符外):
If I run the code from the first three answers I get the same result(except for the delimeter):
但是我的想法是在A列中获取00:00,在B列中获取-6,依此类推.
But my idea it to get 00:00 in column A, -6 in column B and so on..
推荐答案
pandas
方法怎么样?简单又好...
How about a pandas
approach? Nice and simple ...
import pandas as pd
data = [['00:00', 'abc', '2', 'xyz'], ['00:01', 'cde', '3', 'sda']]
cols = ['A', 'B', 'C', 'D']
# Load data into a DataFrame.
df = pd.DataFrame(data, columns=cols)
# Write the CSV.
df.to_csv('output.csv', sep='|', index=False)
根据 docs 您可以使用 sep
参数更改分隔符.
Per the docs you can change the separator using the sep
parameter.
output.csv
的内容,如控制台所示:
Content of output.csv
as shown from the console:
user@host ~/Desktop/so
$ cat output.csv
A|B|C|D
00:00|abc|2|xyz
00:01|cde|3|sda
这篇关于Python:将清单清单写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!