Kla*_*ten 1 python csv excel pandas
我有一个要插入数据库的excel表。我写了一个 python 脚本,它接受一个 excel 文件,将其转换为 CSV,然后将其插入到数据库中。问题是 Excel 工作表包含邮政编码,不幸的是删除了前导零。
这是我读取excel表并将其放入csv的代码:
def excel_to_csv():
xlsx = pd.read_excel(excel_path + fileName + '.xlsx')
xlsx.to_csv(csv_file, encoding='utf-8', index=False, na_rep=None, quoting=csv.QUOTE_NONE)
excel_to_csv()
Run Code Online (Sandbox Code Playgroud)
然后我使用此代码将其插入到数据库中:
with open(csv_file, 'rb') as f:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
next(reader)
for row in reader:
cur.execute(
"INSERT INTO table (foo1, foo2, zipcode, foo3) VALUES (%s, %s, %s, %s); ",
row
)
conn.commit()
Run Code Online (Sandbox Code Playgroud)
当我从 excel 转换后打印出我的 csv 时,我得到了这个结果:
foo1,foo2,zipcode,foo3
353453452,DATA,37,CITY
463464356,DATA,2364,CITY
Run Code Online (Sandbox Code Playgroud)
excel 文件中的邮政编码单元格被转换为文本,因此它保留前导零,但是当我将 excel 文件转换为 csv 时,如何保留前导零?
从文档:
dtype:类型名称或列的字典 -> 类型,默认无
数据或列的数据类型。例如 {'a': np.float64, 'b': np.int32} 使用 object 来保存存储在 Excel 中的数据,而不是解释 dtype。如果指定了转换器,它们将被应用于 dtype 转换的 INSTEAD。
0.20.0 版中的新功能。
因此,您可以pd.read_excel
通过将dtype
-kwarg设置为来判断不解释数据object
:
xlsx = pd.read_excel(excel_path + fileName + '.xlsx', dtype='object')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2556 次 |
最近记录: |