python3.6 报错can't concat str to bytes

文件写入时,报错代码如下:

    out = open(out_file,'w')
    for line in open(in_file,encoding='UTF-8'):
        result = parse_song_line(line) #result是一个字符串
        if(result):
            out.write(result.encode('utf-8').strip()+"\n")  
    out.close()

这是因为encode返回的是bytes型的数据,不可以和str相加,将‘\n’前加b,write函数参数需要为str类型,转化为str即可

代码修改为:

out.write(str(result.encode('utf-8').strip()+b"\n"))  
参考:https://stackoverflow.com/questions/40740150/python-3-cant-concat-bytes-to-str-for-a-list

你可能感兴趣的:(python语法)