简体   繁体   English

如何在Python中转换,排序和保存到CSV MS Access数据库.mdb文件

[英]How to convert, sort and save to CSV MS Access database .mdb file in Python

I tried researching the answer but was not able to find a good solution. 我试图研究答案,但找不到一个好的解决方案。 I have files with strange extensions .res. 我的文件扩展名为.res。 I was told that they are MS Access files. 有人告诉我它们是MS Access文件。 Not sure if they are the same as .mdb but I was able to open them in MS Access. 不知道它们是否与.mdb相同,但是我能够在MS Access中打开它们。 How can I open those files, extract necessary data, sort that data and produce .csv file? 如何打开这些文件,提取必要的数据,对该数据进行排序并生成.csv文件? I tried using this script: http://mazamascience.com/WorkingWithData/?p=168 and mdb tools on Linux. 我尝试使用以下脚本: http : //mazamascience.com/WorkingWithData/? p= 168和Linux上的mdb工具。 I got some output with errors in terminal but all the files produced were blank. 我在终端中得到了一些带有错误的输出,但是生成的所有文件都是空白的。 It could be due to encoding. 这可能是由于编码。 I am not sure. 我不确定。 The file is in ASCII encoding I think. 我认为该文件为ASCII编码。

Error: Table fo_Table
Smart_Battery_Data_Table
MCell_Aci_Data_Table
Aux_Global_Data_Table
Smart_Battery_Clock_Stretch_Table
 does not exist in this database.

On Windows I have no idea how to do it. 在Windows上,我不知道该怎么做。 My first step for now is just to dump the necessary table from that database file into .csv. 我现在的第一步只是将必要的表从该数据库文件转储到.csv中。 But ideally I need the script to take the file, sort it, extract necessary data, do some calculations (like data in one column divided by data in another column) and save all that stuff into nice .csv. 但是理想情况下,我需要脚本来处理文件,对其进行排序,提取必要的数据,进行一些计算(例如将一列中的数据除以另一列中的数据)并将所有内容保存到漂亮的.csv文件中。 Thanks a lot. 非常感谢。 I am not an experienced programmer so please have mercy. 我不是一个经验丰富的程序员,所以请留意。

Using the generic pyodbc library should do it. 使用通用的pyodbc库应该做到这一点。 Looks like it has already an embedded MS access driver. 看起来它已经具有嵌入式MS访问驱动程序。 This question can probably help you out. 这个问题可能可以帮助您。

I dont have any MS Access database files with me (It has been ages that I dont have to work with them), but following the examples your code should be something like this: 我没有任何MS Access数据库文件(已经很多年了,我不必使用它们),但是在示例之后,您的代码应如下所示:

import pyodbc

db_file = r'''/path/to/the/file.res'''
user = 'admin'
password = 'password'
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s;UID=%s;PWD=%s' % (db_file, user, password)

conn = pyodbc.connect(odbc_conn_str)

cursor = conn.cursor()

cursor.execute("select * from table order by some_column")

for row in cursor.fetchall():
    print ", ".join((row.column1, row.column2, row.columnN))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM