2017-01-09 45 views
1

调用data_storage.py中的函数data_save_csv(写入.csv文件中的数据),但它错误:TypeError:类似字节的对象是必需的,而不是 '海峡',你能告诉我该怎么解决呢Python错误:需要类似字节的对象,而不是FBCrawl.py中的'str'

FBCrawl.py:

header = ["id","name","administrator"] 
data_storage.data_save_csv("group_members",group_info_result,"1610393525875114",header) 

data_storage.py:

#write data in .csv file 
def data_save_csv(type,data,id_name,header,since = None): 
    #get the date when storage data 
    date_storage() 
    #create the data storage directory 
    csv_parent_directory = os.path.join("dataset","csv",type,glovar.date) 
    directory_create(csv_parent_directory) 
    #write data in .csv 
    if type == "group_members": 
     csv_file_prefix = "gm" 
    if since: 
     csv_file_name = csv_file_prefix + "_" + since.strftime("%Y%m%d-%H%M%S") + "_" + time_storage() + id_name + ".csv" 
    else: 
     csv_file_name = csv_file_prefix + "_" + time_storage() + "_" + id_name + ".csv" 
    csv_file_directory = os.path.join(csv_parent_directory,csv_file_name) 

    with open(csv_file_directory,'wb') as csvfile: 
     writer = csv.writer(csvfile,delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL) 

     #csv header 

     writer.writerow(header) 

     row = [] 
     for i in range(len(data)): 
      for k in data[i].keys(): 
       row.extend(data[i][k]) 
       writer.writerow(row) 

错误:

C:\Python\Python36\python.exe  
C:/Python/PyCharmProject/FaceBookCrawl/FBCrawl.py 
1060327860756932|Qp-F2RNW_n5HxrVPP2saNJA4PB0 
Traceback (most recent call last): 
File "C:/Python/PyCharmProject/FaceBookCrawl/FBCrawl.py", line 225, in <module> 
data_storage.data_save_csv("group_members",group_info_result,"1610393525875114",header) 
File "C:\Python\PyCharmProject\FaceBookCrawl\data_storage.py", line 43, in data_save_csv 
writer.writerow(header) 
TypeError: a bytes-like object is required, not 'str' 

Process finished with exit code 1 

回答

2

写入器引用的CSV文件是使用wb(写入二进制)标志打开的,这意味着您必须使用字节数组来写入它。

只是转换header到字节数组当你写:

writer.writerow(header.encode()) 

你可以只使用w标志或者打开该文件(这将让你写字符串):

open(csv_file_directory, 'w') 
2

如果您使用python3,写入模式应该是'w',而不是'wb'。

>>> import csv 
>>> headers = ['ab', 'cd'] 
>>> with open('out.csv', 'wb') as f: 
...  writer = csv.writer(f) 
...  writer.writerow(headers) 
... 
Traceback (most recent call last): 
    File "<stdin>", line 3, in <module> 
TypeError: a bytes-like object is required, not 'str' 


>>> with open('out.csv', 'w') as f: 
...  writer = csv.writer(f) 
...  writer.writerow(headers) 
... 
7 
>>> 

“WB”是二进制模式,所以python3假设你会写编码字节串到你的文件; 'w'是文本模式,所以python3需要unicode字符串,这是您的标题列表包含的内容。

+0

就是这样。完全错过了Python3。谢谢@snakecharmerb –

相关问题