将Python列表写入CSV文件

3

我在csv输出文件的格式上遇到了一些困难。

我有一个名为“found”的python列表:

   [['dropbearid', 'distance'],
    ['DB_1487', 17.543651156695343],
    ['DB_1901', 24.735333924441772],
    ['DB_2800', 6.607094868078008]]

当我使用

import csv
out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(found)

我得到了一个文件,当我在Excel中打开时,它有数据但是' dropbearid ', ' distance '在一个单元格中,而 ' DB_1487 ', ' 17.54 ... '在下一个单元格中,以此类推一直延伸到第一行的末尾。

有没有办法将输出设置为'dropbearid'和'distance'放置在两列中,所有列表都放在它们下面的行中?

谢谢!


为了插入每一行,您需要单独调用 out.writerow,或者您可以使用 out.writerows() - ZdaR
使用numpy实现这个非常简单,可以参考这里的stackoverflow链接:https://dev59.com/9m025IYBdhLWcg3wUEOP - Dr G.
6个回答

4

欢迎来到Stackoverflow。您将列表写成一行,这就是为什么一个单元格中有两个值的原因,因为您将found(其中包含两个元素的列表)的每个元素都写入了一个单元格中。您需要遍历列表,并将每个列表写入一行。这应该可以解决问题:

import csv
out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL, newline='')
for row in found:
    out.writerow(row)

1
在writerobj中添加newline='',否则你的文件中会有空行。 - SanthoshSolomon

1

函数writerow()将会写入一行数据。因此,您需要使用writerows()函数并设置newline参数为'',以避免在文件中出现空行。

found = [['dropbearid', 'distance'],
    ['DB_1487', 17.543651156695343],
    ['DB_1901', 24.735333924441772],
    ['DB_2800', 6.607094868078008]]
import csv
with open('myfile.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
    writer.writerows(found)

希望这有所帮助!干杯!

1
import pandas as pd
found = [['dropbearid', 'distance'],['DB_1487', 17.543651156695343],['DB_1901', 24.735333924441772],['DB_2800', 6.607094868078008]]
dffound = pd.DataFrame(found)
header = dffound.iloc[0]
dffound = dffound[1:]
dffound.rename(columns = header)
dffound.tocsv("enter path here")

0
使用pandas数据框将列表写入CSV文件,可以使格式化更加容易。
import pandas as pd
dffound = pd.DataFrame(found,columns=['dropbearid', 'distance'])
dffound.to_csv('Found.csv')

0

您可以使用writerows函数而不是writerow,将子列表的每个项目作为一列进行写入。

with open('myfile.csv', 'w+') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    writer.writerows(d)

0
使用pandas库来完成此操作。
import pandas as pd
df = pd.DataFrame(found, columns=['dropbearid', 'distance'])
df = df.drop(0) # drop the header row
df.to_csv('Found.csv', index=False)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接