要在Python中把Microsoft Acces表(.accdb)转换成CSV文件,请使用以下四个步骤。
- 建立数据库连接。
- 运行SQL查询来选择数据。
- 使用基本的Python文件I/O和
csv模块将数据存储在CSV中,然后 - 关闭数据库连接。
下面是一个具体的[例子],有额外的注释,并为清晰起见进行了简化。
import pyodbc
import csv
# 1. Example establish database connection
connection = pyodbc.connect("your connection string")
# 2. Run SQL query
cursor = connection.cursor()
cursor.execute('select * from XXX;')
# 3. Store the contents in "cursor" in the CSV using file I/O
with open('my_file.csv','w') as f:
writer = csv.writer(f)
writer.writerows([x[0] for x in cursor.description])
writer.writerows(cursor)
# 4. Close the database connection
cursor.close()
conn.close()
基本上,只要你掌握了使用cursor 变量拉动数据的艺术,你就可以使用各种不同的方式来实现。 [pyodbc](https://blog.finxter.com/how-to-install-pyodbc-in-python/)模块将数据拉入CSV,你就可以使用所有不同的方法,使用基本的Python文件I/O将数据写入CSV,例如 [open()](https://blog.finxter.com/python-open-function/)函数或[上下文][管理器]--甚至是Pandas函数,[将DataFrames写入CSV文件]。