我在Python3.2上,有一个SQL输出,我正在用一个“Name”标识符和一个“specifics”写入CSV文件。对于来自中国的一些数据,人们的名字(也就是汉字)正在被插入。我已经尽力阅读了unicode/解码文档,但是我不知道如何在Python中完整地修改/删除这些字符。在
我是这样浏览文件的:
import csv, os, os.path
rfile = open(nonbillabletest2.csv,'r',newline='')
dataread= csv.reader(rfile)
trash=next(rfile) #ignores the header line in csv:
#Process the target CSV by creating an output with a unique filename per CompanyName
for line in dataread:
[CompanyName,Specifics] = line
#Check that a target csv does not exist
if os.path.exists('test leads '+CompanyName+'.csv') < 1:
wfile= open('test leads '+CompanyName+'.csv','a')
datawrite= csv.writer(wfile, lineterminator='\n')
datawrite.writerow(['CompanyName','Specifics']) #write new header row in each file created
datawrite.writerow([CompanyName,Specifics])
wfile.close()
rfile.close()
我收到这个错误:
^{pr2}$在检查文件内容时,显然有些非UTF8字符:
print(repr(open('nonbillabletest2.csv', 'rb').read()))
b'CompanyName,Specifics\r\neGENTIC,\x86\xac\xff; \r\neGENTIC,\x86\xac\xff; \r\neGENTIC,
\x86\xac\xff; \r\neGENTIC,\x91\x9d?; \r\neGENTIC,\x86\xac\xff; \r\n'
合并“encoding=utf8”并不能解决问题。我已经能够使用…replace('\x86\xac\xff','')删除单个字符,但是我必须对我能输入的每个字符都这样做,这是不高效的。在
如果有SQL解决方案也可以。救命啊!在
更新:我删除了使用字符串。可打印正如有人建议的那样。我又犯了一个错误,因为“目录”部分总是有最后一行。不过,添加if len=0检查可以解决这个问题。在
非常感谢你的快速帮助!在
所以nonbillabletest2.csv不是用UTF-8编码的。在
你可以:
事先删除所有非ascii字符(对于纯粹主义者来说,这会破坏数据,但根据您所说的,这似乎是您可以接受的)
相关问题 更多 >
编程相关推荐