2016-12-14 70 views
1

我似乎遇到打印計數器到csv文件的問題。我試過了線程Python: Writing Counter to a csv fileHow do you write a counter to a file in order?Python: Writing a dictionary to a csv file with one line for every 'key: value',但似乎我一直在陷入問題。在Python錯誤中打印csv文件的計數器

我有反格式化,像這樣:

>>> print(daysCounter) 
Counter({'03/08/2016': 246, '13/12/2016': 220, '22/01/2016': 198, '20/09/2016': 191}) 

計數器要大得多,但是這給格式化想法。

現在,當我嘗試使用(有進口的CSV或更早):

with open('lifetime_edits.csv', 'wb') as csv_file: 
     writer = csv.writer(csv_file) 
     for key, value in daysCounter.items(): 
      writer.writerow([key, value]) 

我得到的錯誤:

Traceback (most recent call last): 
    File "contribs.py", line 138, in <module> 
    lifetime_analysis(data) 
    File "contribs.py", line 91, in lifetime_analysis 
    writer.writerow([key, value]) 
TypeError: a bytes-like object is required, not 'str' 

所以我,我根本就沒有使用的東西正確的假設,和我完全無法理解正在發生的事情。如果有人能夠對我爲什麼解決這個問題提供一些見解,並且如果可能的話,如何解決這個問題,我將非常感激。

注意,本月底的目標將是獲得上述對打印到格式的文件:

03/08/2016,246 
13/12/2016,220 
22/01/2016,198 
20/09/2016,191 

您的關注和時間的感謝。

回答

2
with open('lifetime_edits.csv', 'wb') as csv_file: 

這需要一個字節的輸入,你打開帶有 'B' 模式下的文件,只需使用 'W' 模式,這種模式下默認輸入STR:

with open('lifetime_edits.csv', 'w') as csv_file:

推薦方式:

with open('lifetime_edits.csv', 'w', newline='') as csv_file: 

If newline=」 is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline=」, since the csv module does its own (universal) newline handling.

+0

nnnnngggghhhhhh,是的,這解決了這個問題。謝謝你澄清它。 我不確定它是否相關,但似乎在這個csv文件中每行之間都有一條空行。這是正常的行爲嗎? – Ronan

+0

該代碼工作正常,我不知道是一個系統問題,但在文檔中,有一個安全的方法來做到這一點,我更新了代碼 –

+0

真棒,那加法擺脫了換行符。下次我會保持這種狀態。感謝您的時間! – Ronan