[英]How to write data to CSV file into correct column heading in Python?
我有一個字典數據,我需要將其寫到CSV文件中,標題為“ Form Name Type & Definition
,要寫入的字典數據在下面的代碼片段中。
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
,數據擴大到一些列年輕的標題Definition
。
我到處搜索,但不知道為什么它會像這樣擴展列,或者csv列中的數據量有限? 這有什么問題,如何將其數據寫入CSV文件的正確列? 謝謝。
您可能成功將字典轉換為數據框,然后將其保存到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')
沒有一些示例數據,很難對您的數據進行測試。
問題是csv用特殊字符分隔每列。 在您的情況下,您使用逗號“,”。 但是在您的文本中也會出現逗號。 因此,csv將其用作分隔符,並將其解釋為新列。 您可以從逗號切換為分號“;” 作為分隔符。 但是即使那樣,您仍然必須確保原始文本中沒有分號。
如果采用這種方式,則需要更改以下幾行:
string = string + ";" + col_header # ; instead of ,
string = form + ";" + key + ";" + " " + ";"+value
但我建議使用圖書館,例如@Nathaniel建議
它沒有擴展為相鄰的列; 由於文本的大小,它不適合列寬,Excel的默認設置是在相鄰列上繪制該文本。 您可以通過選擇似乎已擴展到其中的單元格並查看它們實際上為空來驗證這種情況。 您還可以更改這些單元格的顯示方式,將它們的內容“包裝”在提供的列中(使行更高)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.