我有一个字典数据,需要将其写入标题为Form Name Type & Definition
下的CSV文件中,要写入的字典数据在下面的代码段中。
writeData.py
def writeCSV():
# Dictionary Data to write received from Form Submit
csvData = {
'form' : 'Customer',
'Customer [form]' : 'Customer is module for recording information related to customer such as Name, Address, Date of Birth, Place of Birth, ID Number, etc.',
'Salutation [label]' : 'A greeting in words or actions, or the words used at the beginning of a letter or speech. This field has values such as Mr, Ms, Miss.',
'First Name English [label]': 'The name that was given to you when you were born and that comes before your family name. This field accept only English Character.'
}
items = {key:value for key,value in csvData.iteritems() if key != 'form'}
form = csvData.get('form')
Columns = ['Form','Name','Type','Definition']
string = ''
with open("myfile.csv","w+") as f:
# Write Heading
for col_header in Columns:
string = string + "," + col_header
f.write(string[1:]+'\n')
# Write Data Body
string = ''
for key,value in items.iteritems():
string = form + "," + key + "," + " " + ","+value
f.write(string)
f.write('\n')
return ''
writeCSV()
但是,在执行上述python脚本之后,数据已正确写入标题Form
,Name
和Type
下。但是,在标题Definition
下,数据已扩展到更多列。
我搜索了一下,但不知道为什么它会像这样扩展列,或者csv列内部的数据量有限?这有什么问题,如何将其数据写入CSV文件的正确列?谢谢。
答案 0 :(得分:1)
您可能成功将字典转换为数据框,然后将其保存到csv:
import pandas as pd
csvData = {'form' : 'Customer',
'Customer [form]' : 'Customer is module for recording information related to customer such as Name, Address, Date of Birth, Place of Birth, ID Number, etc.',
'Salutation [label]' : 'A greeting in words or actions, or the words used at the beginning of a letter or speech. This field has values such as Mr, Ms, Miss.',
'First Name English [label]': 'The name that was given to you when you were born and that comes before your family name. This field accept only English Character.'
}
# Try either of these
df = pd.DataFrame(csvData, index=[0])
#df = pd.DataFrame.from_dict(csvData)
# Output to csv
df.to_csv('myfile.csv')
没有一些示例数据,很难对您的数据进行测试。
答案 1 :(得分:1)
问题是csv用特殊字符分隔每列。在您的情况下,您使用逗号“,”。但是在您的文本中也会出现逗号。因此,csv将其用作分隔符,并将其解释为新列。您可以从逗号切换为分号“;”作为分隔符。但是即使那样,您仍然必须确保原始文本中没有分号。
如果采用这种方式,则需要更改以下行:
string = string + ";" + col_header # ; instead of ,
string = form + ";" + key + ";" + " " + ";"+value
但是我建议使用类似@Nathaniel建议的库
答案 2 :(得分:0)
它没有扩展为相邻的列;由于文本的大小,它不适合列宽,Excel的默认设置是在相邻列上绘制该文本。您可以通过选择似乎已扩展到其中的单元格并查看它们实际上为空来验证这种情况。您还可以更改这些单元格的显示方式,将它们的内容“包装”在提供的列中(使行更高)。