编辑:我已将此放入标题中,但刚意识到我在正文中没有提及。这似乎是特定于Windows的。
我在编写一个脚本,使用csv
Python模块输出内容时遇到了困难,因为该脚本需要同时支持Python 2.7和3.3。
第一次尝试在Python 2.7中按预期工作:
with open('test.csv', 'wb') as csv_file:
writer = csv.DictWriter(csv_file, ['header1', 'header2'])
writer.writeheader()
for item in items:
writer.writerow(item)
然而,当在Python 3.3中运行相同的东西时,你最终会得到:
TypeError: 'str' does not support the buffer interface
所以我将'wb'
更改为'wt'
,程序可以运行,但现在文件中每隔一行会有一个额外的空行。
为了解决这个问题,我进行了以下更改:
with open('test.csv', 'wt') as csv_file:
with open('test.csv', 'wt', newline='') as csv_file:
但现在它无法运行在Python 2.7上:
TypeError: 'newline' is an invalid keyword argument for this function
我知道我可以做这样的事情:
try:
with open('test.csv', 'wt', newline='') as csv_file:
writer = csv.DictWriter(csv_file, ['header1', 'header2'])
writer.writeheader()
for item in items:
writer.writerow(item)
except TypeError:
with open('test.csv', 'wb') as csv_file:
writer = csv.DictWriter(csv_file, ['header1', 'header2'])
writer.writeheader()
for item in items:
writer.writerow(item)
然而,这有一些严重的重复。
是否有更清晰的方法来做到这一点?
编辑:测试数据很简单,没有换行符或其他任何东西:
items = [{'header1': 'value', 'header2': 'value2'},
{'header1': 'blah1', 'header2': 'blah2'}]
'w'
代替'wb'
或'wt'
吗? - nathancahillitems
列表中的字符串是unicode
字符串吗?这些值始终为ASCII码,还是可能包含需要进行编码的其他字符?即使您能够在两个Python版本下运行相同的代码,您也可能得不到相同的结果! - Blckknght