感謝您的幫助。我是SQLite3的新手,確實混淆了兩者。我已經嘗試了下面的代碼,但它仍然不起作用。Python和sqlite3 - 將文本文件導入數據庫
import csv
import sqlite3
# Create the database
connection = sqlite3.connect('addresses.db')
cursor = connection.cursor()
# Create the table
cursor.execute('DROP TABLE IF EXISTS addresses')
cursor.execute('''CREATE TABLE addresses
(ID text, Firstname text, Surname text, Address1 text, Address2 text, Postcode text)''')
connection.commit()
# Load the CSV file into CSV reader
csvfile = open('addresses.txt', 'r')
creader = csv.reader(csvfile, delimiter=',', quotechar='"')
# Iterate through the CSV reader, inserting values into the database
for t in creader:
cursor.execute('INSERT INTO addresses VALUES (?,?,?,?,?,?)', t)
# Close the csv file, commit changes, and close the connection
csvfile.close()
connection.commit()
connection.close()
我得到的錯誤
在creader T: 文件 「/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py」,第26行,在解碼 返回codecs.ascii_decode(輸入,self.errors)[0] UnicodeDecodeError錯誤: 'ASCII' 編解碼器不能在位置0解碼字節0xe2:在範圍序數不(128)
你說你要加載一個叫做'名字的文件。 txt'到數據庫中,但你實際上加載了一個文件'addresses.txt' ...對不起,提出明顯的,但有時... :-) – zmo
對不起,我的錯字。感謝您的發現 - 我希望這很簡單! – g3561