I am trying to export an output file as a CSV file.
我正在尝试将输出文件导出为CSV文件。
I have 15 columns and 400 rows.
我有15列和400行。
In my code, I stored data in the dictionary file, which means that I have one dictionary for each column.
在我的代码中,我将数据存储在字典文件中,这意味着每列都有一个字典。
So I want to get a CSV file which includes all dictionary in the same file.
I tried to use a (for) loop in order to do that, but it did not work.
所以我想获得一个CSV文件,其中包含同一文件中的所有字典。我尝试使用(for)循环来做到这一点,但它没有用。
2 个解决方案
#1
0
use Pandas libray
let us Assume your dictionary is like this:
让我们假设你的字典是这样的:
my_dict = {'key1': '1', 'key2': 'b', 'key3': '123'}
To tackle your problem use :
要解决您的问题,请使用:
import pandas as pd
(pd.DataFrame.from_dict(data=mydict, orient='columns')
.to_csv('file_name.csv', header=False))
See Ivan Calderon's Answer for more information.!!
有关更多信息,请参阅Ivan Calderon的答案。!!
#2
0
Please Check the variable as per your need. This should work.
请根据您的需要检查变量。这应该工作。
def WriteCsv(csvFileName, csvFieldNames, row=None ):
import csv
import os
if row:
if os.path.exists(csvFileName):
f_handle = open(csvFileName, 'a')
csvWriter = csv.DictWriter(f_handle, fieldnames=csvFieldNames)
else:
f_handle = open(csvFileName, 'w+')
csvWriter = csv.DictWriter(f_handle, fieldnames=csvFieldNames)
csvWriter.writeheader()
try:
csvWriter.writerow(row)
finally:
f_handle.close()
for row in dict_data:
WriteCsv(csvFileName="Names.csv",csvFieldNames=csv_columns,row=row)
#1
0
use Pandas libray
let us Assume your dictionary is like this:
让我们假设你的字典是这样的:
my_dict = {'key1': '1', 'key2': 'b', 'key3': '123'}
To tackle your problem use :
要解决您的问题,请使用:
import pandas as pd
(pd.DataFrame.from_dict(data=mydict, orient='columns')
.to_csv('file_name.csv', header=False))
See Ivan Calderon's Answer for more information.!!
有关更多信息,请参阅Ivan Calderon的答案。!!
#2
0
Please Check the variable as per your need. This should work.
请根据您的需要检查变量。这应该工作。
def WriteCsv(csvFileName, csvFieldNames, row=None ):
import csv
import os
if row:
if os.path.exists(csvFileName):
f_handle = open(csvFileName, 'a')
csvWriter = csv.DictWriter(f_handle, fieldnames=csvFieldNames)
else:
f_handle = open(csvFileName, 'w+')
csvWriter = csv.DictWriter(f_handle, fieldnames=csvFieldNames)
csvWriter.writeheader()
try:
csvWriter.writerow(row)
finally:
f_handle.close()
for row in dict_data:
WriteCsv(csvFileName="Names.csv",csvFieldNames=csv_columns,row=row)