Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Python 3:不带b'的持久化字符串;_String_Python 3.x_Csv - Fatal编程技术网

String Python 3:不带b'的持久化字符串;

String Python 3:不带b'的持久化字符串;,string,python-3.x,csv,String,Python 3.x,Csv,我很困惑。这说明,您应该在代码中只使用unicode字符串。当字符串离开代码时,应该将它们转换为字节。我这样做是为了一个csv文件: import csv with open('keywords.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile, delimiter='\t', quotechar='\"') for (p, keywords) in ml_data: writer.wr

我很困惑。这说明,您应该在代码中只使用unicode字符串。当字符串离开代码时,应该将它们转换为字节。我这样做是为了一个csv文件:

import csv

with open('keywords.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter='\t', quotechar='\"')
    for (p, keywords) in ml_data:
        writer.writerow([p.encode("utf-8"), ', '.join(keywords).encode("utf-8")])

这导致了一种恼人的效果,即在每个字符串前面添加了
b'
,而在python 2.7中我没有这样做。如果在将字符串写入csv文件之前未对其进行编码,则不存在
b'
,但在持久化时不需要将其转换为字节吗?如何将字节写入文件而不受此困扰?

停止尝试对单个字符串进行编码,而应指定整个文件的编码:

import csv

with open('keywords.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile, delimiter='\t', quotechar='\"')
    for (p, keywords) in ml_data:
        writer.writerow([p, ', '.join(keywords)])
代码出错的原因是
writerow
希望您为其提供字符串,但您正在传递字节,因此它使用字节的
repr()
,该字节周围有额外的
b'.
。如果在打开文件时传递字符串,但使用
编码
参数,则字符串将为您正确编码


看。其中一个演示如何设置编码。

好的,谢谢。我打赌它在Python2.7中起作用,因为实际上有字节字符串,它们被认为是字符串。在Python3.x中,只有unicode字符串,对吗?