如何用Python处理.mdb访问文件
有没有人能告诉我怎么在Python里打开一个.mdb文件?我通常喜欢先写点代码来开始讨论,但我不知道从哪里入手。我在Python中经常使用mysql。我想知道有没有办法像处理mysql那样处理.mdb文件?
7 个回答
4
这看起来和之前的一个问题很相似:
- 我需要什么才能用Python读取Microsoft Access数据库?
- http://code.activestate.com/recipes/528868-extraction-and-manipulation-class-for-microsoft-ac/
那里的回答应该会对你有帮助。
16
有一个叫做 meza 的库,是Reuben Cummings开发的,它可以通过 mdbtools 来读取Microsoft Access数据库。
安装
# The mdbtools package for Python deals with MongoDB, not MS Access.
# So install the package through `apt` if you're on Debian/Ubuntu
$ sudo apt install mdbtools
$ pip install meza
使用方法
>>> from meza import io
>>> records = io.read('database.mdb') # only file path, no file objects
>>> print(next(records))
Table1
Table2
…
65
下面是我为另一个SO问题写的一些代码。
它需要使用第三方的pyodbc模块。
这个非常简单的例子将连接到一个表,并把结果导出到一个文件中。
如果你有更具体的需求,欢迎在你的提问中补充。
import csv, pyodbc
# set up some constants
MDB = 'c:/path/to/my.mdb'
DRV = '{Microsoft Access Driver (*.mdb)}'
PWD = 'pw'
# connect to db
con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV,MDB,PWD))
cur = con.cursor()
# run a query and get the results
SQL = 'SELECT * FROM mytable;' # your query goes here
rows = cur.execute(SQL).fetchall()
cur.close()
con.close()
# you could change the mode from 'w' to 'a' (append) for any subsequent queries
with open('mytable.csv', 'w') as fou:
csv_writer = csv.writer(fou) # default field-delimiter is ","
csv_writer.writerows(rows)