将python列表编写为CSV
只是有一点挣扎获得正确的格式与csv输出文件 我有一个名为Find in python的列表:将python列表编写为CSV,python,Python,只是有一点挣扎获得正确的格式与csv输出文件 我有一个名为Find in python的列表: [['dropbearid', 'distance'], ['DB_1487', 17.543651156695343], ['DB_1901', 24.735333924441772], ['DB_2800', 6.607094868078008]] 当我使用 import csv out = csv.writer(open("myfile.csv","w"), de
[['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”放在两列中,并将下面的所有列表放在下面的行中
谢谢 欢迎来到Stackoverflow。您将列表列表写入一行,这就是为什么在一个单元格中有两个值,因为您在一个单元格中写入找到的
的每个元素(这是两个元素的列表)。您需要遍历列表列表并将每个列表写入一行。这应该起作用:
import csv
out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL, newline='')
for row in found:
out.writerow(row)
函数writerow()
将写入一行。因此,您需要使用writerows()
并将换行符
参数设置为'
,以避免文件中出现空行
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)
希望这有帮助!干杯 使用pandas数据框将列表写入CSV,这使格式设置更加容易
import pandas as pd
dffound = pd.DataFrame(found,columns=['dropbearid', 'distance'])
dffound.to_csv('Found.csv')
您可以使用writerows函数而不是writerow,将子列表的每一项作为列写入
with open('myfile.csv', 'w+') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerows(d)
使用熊猫图书馆进行此操作
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)
要插入每一行,您需要分别调用out.writerow
,或者您可以使用out.writerows()
非常简单的方法,在这里使用numpy在writerobj中添加换行符='',否则您的文件中会出现空行。
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)