我试图用一个Python 3.4应用程序将一个管道分隔的文本文件导入到一个现有的表中,但是我遇到了一些麻烦。
应用程序将用于导入不同的文本文件,因此我使用一个entry小部件来写入文件名,并希望将输入的文件内容加载到我的表中。我试着使用access将文件加载到able中,它工作得很好,因此格式应该很好。下面是一些代码,我已经尝试了我的功能没有用。
def insert_data():
inputfile = filepath.get()
fobj = open(inputfile)
cur.execute("""SELECT * INTO text_file_data
FROM [odbc;Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq='{fobj}';];)"""
.format(fobj=fobj))
conn.commit()
给出以下信息:
Tkinter回调异常
回溯(最近一次呼叫时间):
文件“c:\ python34\lib\tkinter_uuu init_uuu.py”,第1487行,调用中
返回self.func(参数)
文件“c:/users/amarquart/pycharmprojects/database testing/source/dbtesting.py”,第267行,运行中
插入数据()
文件“c:/users/amarquart/pycharmprojects/database testing/source/dbtesting.py”,第25行,插入数据
.格式(fobj=fobj)
keyerror:'Microsoft文本驱动程序('
和
def insert_data():
inputfile = filepath.get()
fobj = open(inputfile)
cur.execute("""SELECT * INTO text_file_data
FROM [Text;HDR=Yes;FMT=Delimited;Database=C:\Users\amarquart\Documents\functionDB.mdb].;{fobj}')"""
.format(fobj=fobj))
conn.commit()
给出以下信息:
文件“c:/users/amarquart/pycharmprojects/database testing/source/dbtesting.py”,第24行
从[text;hdr=yes;fmt=delimited;database=c:\users\amarquart\documents\functiondb.mdb]。;{fobj}')”
syntaxerror:(unicode错误)“unicodescape”编解码器无法解码位置93-94中的字节:截断的\uxxxxx转义
其他相关信息
数据库文件路径:c:\ alex\functiondb.mdb
与FOBJ变量一起使用的文件路径:C:\users\amarquart\documents\5.txt
表名:文本文件数据
使用pyodbc进行连接
任何帮助都将不胜感激。
谢谢,
亚历克斯
编辑
我的文本文件没有标题,下面是一个示例
D 1 502 2013 073306586 479.18
最新尝试:
def insert_data():
inputfile = filepath.get()
fobj = open(inputfile)
cur.execute("""INSERT INTO text_file_data (Letter, [Number], Batch, [Year], Parcel, Amount)
VALUES ([Text;FMT=Delimited(|);HDR=NO;DATABASE=C:\Alex\functionDB.mdb].
['{fobj}')]""").format(fobj=fobj)
conn.commit()
给我以下信息:
Tkinter回调异常
回溯(最近一次呼叫时间):
文件“c:\ python34\lib\tkinter_uuu init_uuu.py”,第1487行,调用中
返回self.func(*args)
文件“c/users/amarquart/pycharmprojects/database testing/source/dbtesting.py”,第269行,运行中
插入数据()
文件“c:/users/amarquart/pycharmprojects/database testing/source/dbtesting.py”,第26行,插入数据
['{fobj}')]“”。格式(fobj=fobj)
pyodbc。错误:('21s01','[21s01][microsoft][odbc microsoft access driver]查询值和目标字段的数目不同。(-3520)(sqlexecdirectw)')
编辑
知道了
这和我在网上找到的所有东西都不一样,但它是有效的。它把文本文件中的所有数据都放到数据库中,数据的顺序不一样,但这并不重要。
def insert_data():
inputfile = filepath.get()
fobj = open(inputfile)
for line in fobj:
column = line.split('|')
a = str(column[0])
b = int(column[1])
c = int(column[2])
d = str(column[3])
e = str(column[4])
f = Decimal(column[5])
cur.execute('''INSERT INTO text_file_data ([Letter], [Number], [Batch], [Year], [Parcel], [Amount])
VALUES ('{a}', '{b}', '{c}', '{d}', '{e}', '{f}')'''.format(a=a, b=b, c=c, d=d, e=e, f=f))
conn.commit()
编辑,再看一遍
def insert_data():
inputfile = filepath.get()
qry = """INSERT INTO text_file_data ([Letter], [Number], [Batch], [Year], [Parcel], [Amount])
VALUES (?,?,?,?,?,?)"""
with open(inputfile) as pipeFile:
for line in pipeFile:
cur.execute(qry, line.split("|"))
conn.commit()
这也行,可能更好?
谢谢大家的帮助!
最佳答案
使用Python2.7和PyPyODBC,我得到了这样的工作…
# -*- coding: utf-8 -*-
import os
import pypyodbc
workingFolder = "C:\\Users\\Gord\\Desktop\\"
pipeFileName = "stuff.txt"
commaFileName = "stuff.csv"
with open (workingFolder + pipeFileName, "r") as pipeFile:
data = pipeFile.read()
with open (workingFolder + commaFileName, "w") as commaFile:
commaFile.write(data.replace("|",","))
connStr = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' +
r'DBQ=C:\Users\Public\Database1.accdb'
)
db = pypyodbc.connect(connStr)
qry = """INSERT INTO text_file_data ([Letter], [Number], [Batch], [Year], [Parcel], [Amount])
SELECT F1, F2, F3, F4, F5, F6
FROM [Text;FMT=Delimited;HDR=NO;IMEX=2;CharacterSet=437;Database="""
qry += workingFolder + "].[" + commaFileName.replace(".","#") + "]"
crsr = db.cursor()
crsr.execute(qry)
db.commit()
db.close()
os.remove(workingFolder + commaFileName)
…但它从[包裹]字段中去掉了前导零。这似乎更有效(但不确定速度):
# -*- coding: utf-8 -*-
import pypyodbc
connStr = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' +
r'DBQ=C:\Users\Public\Database1.accdb'
)
db = pypyodbc.connect(connStr)
qry = """INSERT INTO text_file_data ([Letter], [Number], [Batch], [Year], [Parcel], [Amount])
VALUES (?,?,?,?,?,?)"""
crsr = db.cursor()
with open (r"C:\Users\Gord\Desktop\stuff.txt", "r") as pipeFile:
for line in pipeFile:
crsr.execute(qry, line.split("|"))
db.commit()
db.close()
关于python - 使用Python将文本文件导入Access 2003数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25510786/