简体   繁体   English

Python 错误:需要类似字节的对象,而不是“str”

[英]Python error:a bytes-like object is required, not 'str'

in FBCrawl.py call the function data_save_csv(write data in .csv file) in data_storage.py, but it errors:TypeError: a bytes-like object is required, not 'str', could you please tell me how to solve it在 FBCrawl.py 中调用 data_storage.py 中的函数 data_save_csv(write data in .csv file),但它错误:TypeError: a bytes-like object is required, not 'str', 你能告诉我如何解决它

FBCrawl.py: FBCrawl.py:

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

data_storage.py:数据存储.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)

error:错误:

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

You CSV file to which the writer refers was opened with a wb (write binary) flag, which means you have to use byte arrays to write to it.写入者引用的 CSV 文件是用wb (写入二进制)标志打开的,这意味着您必须使用字节数组来写入它。

Just convert header to byte array when you write:编写时只需将header转换为字节数组:

writer.writerow(header.encode())

You can alternatively open the file using only w flag (that will allow you to write strings):您也可以仅使用w标志打开文件(这将允许您编写字符串):

open(csv_file_directory, 'w')

If you are using python3, the write mode should be 'w', not 'wb'.如果您使用的是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', newline='') as f:
...     writer = csv.writer(f)
...     writer.writerow(headers)
... 
7
>>> 

'wb' is binary mode , so python3 assumes that you will be writing encoded bytestrings to your file; 'wb' 是二进制模式,因此 python3 假设您将编码的字节串写入文件; 'w' is text mode , so python3 expects unicode strings, which is what your header list contains. 'w' 是text mode ,因此 python3 需要 unicode 字符串,这是您的标题列表包含的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python需要类似字节的对象,而不是&#39;str&#39; - Python a bytes-like object is required, not 'str' python错误TypeError:需要一个类似字节的对象,而不是&#39;str&#39; - python error TypeError: a bytes-like object is required,not 'str' Python SocketServer 错误:TypeError:需要类似字节的对象,而不是“str” - Python SocketServer Error : TypeError: a bytes-like object is required, not 'str' 错误:需要一个类似字节的对象,而不是“ str”(cPickle,Python) - Error: a bytes-like object is required, not 'str' (cPickle, Python) 需要类似 object 的字节,而不是 python 中的“str”错误 - a bytes-like object is required, not 'str' error in python Python错误:TypeError:需要一个类似字节的对象,而不是&#39;str&#39; - Python error: TypeError: a bytes-like object is required, not 'str' “需要类似字节的 object,而不是 str” Python 中的错误 - “A bytes-like object is required, not str” Error in Python 需要一个类似字节的对象,而不是'str' - 错误 - a bytes-like object is required, not 'str' - error 错误:需要一个类似字节的对象,而不是&#39;str&#39; - Error: a bytes-like object is required, not 'str' Python 错误类型错误:需要类似字节的 object,而不是“str” - Python ERROR TypeError: a bytes-like object is required, not 'str'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM