【发布时间】:2016-08-15 04:35:17
【问题描述】:
使用熊猫 18.1...
我正在尝试遍历 CSV 文件夹以读取每个 CSV 并将其发送到 Oracle 数据库表。在我的许多 CSV 之一中潜伏着一个非 ascii 字符(更像是陶醉于我的痛苦中)。我不断收到此错误:
UnicodeEncodeError: 'ascii' codec can't encode character '\xab' in position 8:
ordinal not in range(128)
代码如下:
import pandas as pd
import pandas.io.sql as psql
from sqlalchemy import create_engine
import cx_Oracle as cx
engine = create_engine('oracle+cx_oracle://schema:'+pwd+'@server:port/service_name'
,encoding='latin1')
name='table'
path=r'path_to_folder'
filelist = os.listdir(path)
for file in filelist:
df = pd.read_csv(pathc+'\\'+file,encoding='latin1',index_col=0)
df=df.astype('unicode')
df['date'] = pd.to_datetime(df['date'])
df['date'] = pd.to_datetime(df['Contract_EffDt'],format='%YYYY-%mm-%dd')
df.to_sql(name, engine, if_exists = 'append')
我尝试了以下方法:
- encoding=utf-8(在引擎中,如果我在 read_csv 中这样做,会引发错误)
- 在引擎中的“service_name”之后添加 ?encoding=utf8
- 使用 df=df.astype('unicode')(而不是)
我想做的事: 用其他东西替换不可读的字符,最重要的是,继续向 Oracle 发送数据。
注意:
我使用的数据文件来自 cms.gov 网站。 Here's a zip file with an example。我正在使用“contracts_info”文件。
提前致谢!
【问题讨论】:
标签: oracle python-3.x sqlalchemy