[python error resolution] TypeError: a bytes-like object is required, not 'str'

In the python2 version,
when opening the csv file, use the binary mode to open it, that is, the way with b, such as wb, ab, etc., but not the text mode, such as w, w+, a+, etc. Otherwise, using witerrow to write will generate blank lines.

But in the python3 version, if you directly use wb to write to open the file, an error will also occur, as follows:

filename3="6-cos-result.csv"
out = open(filename3,'wb+')
csv_write = csv.writer(out,dialect='excel')
    
data_num=100#
for n in range(0,100):
    print ("第",str(n+1),"个目标用户")
    m=11
    for k in range(m):

        if index1[k][n]!=n:
            temp=[]
            num=int(index1[k][n])
            temp.append(num+1)
            temp.append(data1[k][n])
            csv_write.writerow(temp)     
out.close()

An error occurred:
Traceback (most recent call last):
insert image description here

At this time, change out = open(filename3,'wb+') to out = open(filename3,'w+'), and
the program runs normally at this time, but there are blank lines in the written form, as follows:

insert image description here
At this point, you need to use the with open(filename3,'w',newline='') as f: statement to eliminate the problem of blank lines:

filename3="6-cos-result.csv"
with open(filename3,'w',newline='') as f:
    csv_write=csv.writer(f,dialect='excel')
        
data_num=100#
for n in range(0,100):
    print ("第",str(n+1),"个目标用户")
    m=11
    for k in range(m):

        if index1[k][n]!=n:

            temp=[]
            num=int(index1[k][n])
            temp.append(num+1)
            temp.append(data1[k][n])
            csv_write.writerow(temp)       
f.close()

At this point, due to indentation issues, an error occurs:

insert image description here

filename3="6-cos-result.csv"
with open(filename3,'w',newline='') as f:
    csv_write=csv.writer(f,dialect='excel')

    data_num=100#
    for n in range(0,100):
        print ("第",str(n+1),"个目标用户")
        m=11
        for k in range(m):

            if index1[k][n]!=n:    
                temp=[]
                num=int(index1[k][n])
                temp.append(num+1)
                temp.append(data1[k][n])
                csv_write.writerow(temp)
      
f.close()

The error is resolved and the program executes normally

Guess you like

Origin blog.csdn.net/weixin_41824534/article/details/111596427