Python OrderedDict 到 CSV:消除空行

Python OrderedDict to CSV: Eliminating Blank Lines

当我运行这个代码...

from simple_salesforce import Salesforce
sf = Salesforce(username='un', password='pw', security_token='tk')
cons = sf.query_all("SELECT Id, Name FROM Contact WHERE IsDeleted=false LIMIT 2")

import csv

with open('c:\test.csv', 'w') as csvfile:
    fieldnames = ['contact_name__c', 'recordtypeid']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for con in cons['records']:    
        writer.writerow({'contact_name__c': con['Id'], 'recordtypeid': '082I8294817IWfiIWX'})

print('done')

我在 CSV 文件中得到以下输出...

contact_name__c,recordtypeid

xyzzyID1xyzzy,082I8294817IWfiIWX

abccbID2abccb,082I8294817IWfiIWX

我不确定为什么会有这些额外的行。

有什么技巧可以去除它们,使我的 CSV 文件看起来正常吗?

根据 sys.version_info 我在 Python 3.4.3。


这里还有一些代码和输出对,以显示我正在处理的数据类型:

from simple_salesforce import Salesforce
sf = Salesforce(username='un', password='pw', security_token='tk')
print(sf.query_all("SELECT Id, Name FROM Contact WHERE IsDeleted=false LIMIT 2"))

生产

OrderedDict([('totalSize', 2), ('done', True), ('records', [OrderedDict([('attributes', OrderedDict([('type', 'Contact'), ('url', '/services/data/v29.0/sobjects/Contact/xyzzyID1xyzzy')])), ('Id', 'xyzzyID1xyzzy'), ('Name', 'Person One')]), OrderedDict([('attributes', OrderedDict([('type', 'Contact'), ('url', '/services/data/v29.0/sobjects/Contact/abccbID2abccb')])), ('Id', 'abccbID2abccb'), ('Name', 'Person Two')])])])

from simple_salesforce import Salesforce
sf = Salesforce(username='un', password='pw', security_token='tk')
cons = sf.query_all("SELECT Id, Name FROM Contact WHERE IsDeleted=false LIMIT 2")
for con in cons['records']:
    print(con['Id'])

生产

xyzzyID1xyzzy
abccbID2abccb

两种可能的可能性:输出文件需要以二进制模式打开and/or需要告诉编写者不要使用 DOS 风格的行结尾。

在 Python 中以二进制模式打开文件 3 将您当前的 with open 行替换为:

with open('c:\test.csv', 'w', newline='') as csvfile:

要消除 DOS 风格的行结尾,请尝试:

writer = csv.DictWriter(csvfile, fieldnames=fieldnames, lineterminator="\n")