![](/img/trans.png)
[英]UnicodeDecodeError: 'ascii' codec can't decode byte with reading CSV
[英]'ascii' codec can't decode - CSV to SQL Server via pyodbc
我搜索了許多示例,但沒有一個能夠解決我的特定問題。 感謝您抽出寶貴的時間,因為我一生無法找到解決方法。 我正在嘗試使用Python中的for循環將CSV文件插入Azure SQL Server數據庫。 我已經多次使用相同的python程序,將使用多個不同的CSV文件,因此我知道當前CSV的根本問題是。 以下是我的Python代碼的簡短摘要以及錯誤。 我如何編碼CSV以便不再發生此錯誤(如前所述,我嘗試了多個相似線程的解決方案,但無法解決此問題)。
碼:
csvfile = open('C:\\file.csv', 'r')
csv_data = csv.reader(csvfile)
SQL = """Insert into Idea_Pipeline( [col_1], [col_2], [col_3], [col_4])
values (?,?,?,?)
for row in csv_data:
first_row = next(csv_data)
cursor2.execute(SQL, row)
如前所述,這只是我的代碼的一部分,但是我已經使用了無數次,所以我知道語法是正確的。 以下是我無法解決的錯誤。
錯誤:
Traceback (most recent call last):
File "Idea_Pipeline.py", line 46, in <module>
cursor2.execute(SQL, row)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x96 in position 114:
ordinal not in range(128)
再次感謝您提供的所有幫助。
另外-我嘗試了將此CSV批量插入本地SQL Server數據庫,並收到錯誤“操作系統錯誤代碼(空)”
再次感謝您提供的幫助或建議,因為我還比較陌生,並且正在努力學習盡可能多的東西。
聽起來這是您的CSV文件第一次包含'ascii'編解碼器無法處理的字符。 0x96
不是latin1
字符集中的字符之一,因此下一個最可能的候選者可能是windows-1252
,其中0x96
代表“ En Dash”字符(U + 2013)。 如果是這樣的話
# -*- coding: windows-1252 -*-
import csv
import pyodbc
import sys
print("Python version " + sys.version)
print("pyodbc version " + pyodbc.version)
cnxn = pyodbc.connect("DSN=myDb", autocommit=True)
crsr = cnxn.cursor()
crsr.execute("CREATE TABLE #foo (id INT PRIMARY KEY, txtcol VARCHAR(50))")
with open(r'C:\Users\gord\Desktop\sample.csv', 'rb') as csvfile:
csv_data = csv.reader(csvfile)
sql = "Insert into #foo ([id], [txtcol]) VALUES (?,?)"
print("")
print("Rows retrieved from CSV file:")
for row in csv_data:
print(row)
crsr.execute(sql, [cell.decode('windows-1252') for cell in row])
print("")
print("Values retrieved from table:")
for row in crsr.execute("SELECT * FROM #foo").fetchall():
print(row)
cnxn.close()
將產生以下輸出
Python version 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)]
pyodbc version 4.0.16
Rows retrieved from CSV file:
['1', 'foo']
['2', 'test\x96data']
Values retrieved from table:
(1, u'foo')
(2, u'test\u2013data')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.