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

前端 未结 9 2056
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: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

提交回复
热议问题