Python 2.6,升级不是一个选择
脚本旨在从 arcgis 数据库中获取字段并创建将 Oracle 语句插入到文本文件中以供以后使用。 3000 条记录后有 7500 条记录出错,并指出问题所在。
fieldValue = unicode(str(row.getValue(field.name)),'utf-8',errors='ignore')
我已经尝试了unicode和encode的几乎所有变体。我是 python 新手,真的只需要有经验的人来查看我的代码并找出问题所在。
import arcpy
#Where the GDB Table is located
fc = "D:\GIS Data\eMaps\ALDOT\ALDOT_eMaps_SignInventory.gdb/SignLocation"
fields = arcpy.ListFields(fc)
cursor = arcpy.SearchCursor(fc)
#text file output
outFile = open(r"C:\Users\kkieliszek\Desktop\transfer.text", "w")
#insert values into table billboard.sign_inventory
for row in cursor:
outFile.write("Insert into billboard.sign_inventory() Values (")
for field in fields:
fieldValue = unicode(str(row.getValue(field.name)),'utf-8',errors='ignore')
if row.isNull(field.name) or fieldValue.strip() == "" : #if field is Null or a Empty String print NULL
value = "NULL"
outFile.write('"' + value + '",')
else: #print the value in the field
value = str(row.getValue(field.name))
outFile.write('"' + value + '",')
outFile.write("); \n\n ")
outFile.close() # This closes the text file
错误代码:
Traceback (most recent call last):
File "tablemig.py", line 25, in <module>
fieldValue = unicode(str(row.getValue(field.name)),'utf-8',errors='ignore')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 76: ordinal not in range(128)
最佳答案
永远不要在 unicode
对象上调用 str()
:
>>> str(u'\u2019')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 0: ordinal not in range(128)
要以 csv 格式写入包含 Unicode 字符串的行,请使用 UnicodeWriter
而不是手动格式化字段。它应该一次解决几个问题。
关于python - ascii 编解码器无法对超出范围的字符 u'\u2019' 进行编码(128),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32747648/