【发布时间】:2013-06-15 12:18:33
【问题描述】:
我对 Python 还很陌生,因此我们将不胜感激。我正在尝试在 Linux 上使用 mdbtools 从 2000 个 .mdb 文件中提取和排序数据。到目前为止,我能够获取 .mdb 文件并将所有表转储到 .csv 中。它造成了巨大的混乱,因为有很多文件需要处理。
我需要的是从特定表中提取特定的排序数据。例如,我需要名为“Voltage”的表。该表由许多循环组成,每个循环也有几行。周期通常按时间顺序排列,但在某些情况下,时间戳会延迟记录。就像周期的第一行可能比周期 1 的第一行有更晚的时间。我需要根据第一个或最后五个周期的时间提取周期的最新行。例如,在下表中,我将需要第二行。
Cycle# Time Data
1 100.59 34
1 101.34 54
1 98.78 45
2
2
2 ...........
这是我使用的脚本。我正在使用命令python extract.py table_files.mdb. 但我希望仅使用 ./extract.py 调用该脚本。文件名的路径应该在脚本本身中。
import sys, subprocess, os
DATABASE = sys.argv[1]
subprocess.call(["mdb-schema", DATABASE, "mysql"])
# Get the list of table names with "mdb-tables"
table_names = subprocess.Popen(["mdb-tables", "-1", DATABASE],
stdout=subprocess.PIPE).communicate()[0]
tables = table_names.splitlines()
print "BEGIN;" # start a transaction, speeds things up when importing
sys.stdout.flush()
# Dump each table as a CSV file using "mdb-export",
# converting " " in table names to "_" for the CSV filenames.
for table in tables:
if table != '':
filename = table.replace(" ","_") + ".csv"
file = open(filename, 'w')
print("Dumping " + table)
contents = subprocess.Popen(["mdb-export", DATABASE, table],
stdout=subprocess.PIPE).communicate()[0]
file.write(contents)
file.close()
【问题讨论】:
-
我建议将
mdb-export的结果导入SQLite 数据库,然后您可以轻松查询。 -
OP 的上述代码来自okfnlabs.org/handbook/data/patterns/liberating-access-databases,除了在 Python 3 中它工作得很好,因为 Python 3 不像 Python 2 那样使用字节作为默认字符串。对于 Python 3,您必须在带有
communicate()[0]的行中添加类似.decode("utf-8")的内容,例如communicate()[0].decode("utf-8") -
要补充一些已经在这里的答案,使用 accdb/mdb 文件是一种 PITA。似乎没有任何东西(例如 Pandas)支持它,至少在 Windows 上没有微软的专有驱动程序或在 linux/unix 上没有像
mdb-tools这样的第三方库......所以使用 Access 文件的最佳方法是将它们转换为更标准的东西像 CSV 或 SQL 一样,然后进行过滤/排序/转换/等。
标签: python database ms-access csv mdbtools