需要关于通过python输出csv的帮助吗

2024-03-29 07:43:06 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我有三个数据列表。每一个都有不同的长度,它们之间没有关联。你知道吗

我遇到的问题是,当我去写bList时,它会写到我完成的行之后。所以它们都在适当的列中,这很好,但我只希望每列从第2行开始(第1行是为标题保留的)。相反,我让aList从第1行开始,在第28行结束,然后bList从29行开始,以此类推

这是我所拥有的,我希望你们中的一个优秀的巫师能够解释如何修复它。我知道是什么导致了这个问题,我只是不知道如何解决它。你知道吗

def write_output(file):
    f = open(file, 'w')
    fields = ('a', 'b', 'c')
    wr = csv.DictWriter(f, delimiter=",", fieldnames=fields, lineterminator = '\n')

    wr.writeheader()
    for row in aList:
        wr.writerow({'a':row})
    for row in bList:
        wr.writerow({'b':row})
    for row in cList:
        wr.writerow({'c':row})

Tags: 数据in标题fields列表fordefwr
2条回答

下面是一个完整的例子。你知道吗

此脚本不使用任何库,在Python 2.7中运行。只要确保每个值都用逗号分隔,就可以创建CSV(逗号分隔值)文件。另外,我没有使用itertools,而是使用map函数。你知道吗

# Python 2.7    
# Here is an example of three lists of different lengths
aList = [9,8,2,5,14,6]
bList = [8,7,5,4]
cList = [9,15,25,60,47,88,3]

# Creates your empty CSV file
output_file = open(r'C:\Temp\output.csv', 'w')

# Adds headers in the first row
output_file.write('aList,bList,cList\n')

# Adds all the elements from the lists, row-by-row
for a, b, c in map(None, aList, bList, cList):
    output_file.write('%s,%s,%s\n' % (a, b, c))

# Closes your file
output_file.close()

Python 3中,map函数不再支持None作为映射函数。在这种情况下,来自itertools库的zip_longest函数可能是最干净的方法(注意,在Python 2.7中,来自itertools的函数称为izip_longest

# Python 3.x
import itertools

# Here is an example of three lists of different lengths
aList = [9,8,2,5,14,6]
bList = [8,7,5,4]
cList = [9,15,25,60,47,88,3]

# Creates your empty CSV file
output_file = open(r'C:\Temp\output.csv', 'w')

# Adds headers in the first row
output_file.write('aList,bList,cList\n')

# Adds all the elements from the lists, row-by-row
for a, b, c in itertools.zip_longest(aList, bList, cList):
    output_file.write('%s,%s,%s\n' % (a, b, c))

# Closes your file
output_file.close()

使用拉链。你知道吗

示例:如果列表不包含None值:

from itertools import zip_longest

for a_b_c in zip_longest(aList, bList, cList):
    row = {k: v for k, v in zip(fields, a_b_c) if v is not None}
    wr.writerow(row)

相关问题 更多 >