TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

前端 未结 9 2039
Happy的楠姐
Happy的楠姐 2020-11-22 04:58

I\'ve very recently migrated to Py 3.5. This code was working properly in Python 2.7:

with open(fname, \'rb\') as f:
    lines = [x.strip() for x in f.readli         


        
相关标签:
9条回答
  • 2020-11-22 05:25

    You can encode your string by using .encode()

    Example:

    'Hello World'.encode()
    
    0 讨论(0)
  • 2020-11-22 05:26

    You have to change from wb to w:

    def __init__(self):
        self.myCsv = csv.writer(open('Item.csv', 'wb')) 
        self.myCsv.writerow(['title', 'link'])
    

    to

    def __init__(self):
        self.myCsv = csv.writer(open('Item.csv', 'w'))
        self.myCsv.writerow(['title', 'link'])
    

    After changing this, the error disappears, but you can't write to the file (in my case). So after all, I don't have an answer?

    Source: How to remove ^M

    Changing to 'rb' brings me the other error: io.UnsupportedOperation: write

    0 讨论(0)
  • 2020-11-22 05:26

    for this small example:

    import socket
    
    mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    mysock.connect(('www.py4inf.com', 80))
    mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
    
    while True:
        data = mysock.recv(512)
        if ( len(data) < 1 ) :
            break
        print (data);
    
    mysock.close()
    

    adding the "b" before 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n' solved my problem

    0 讨论(0)
提交回复
热议问题