[英]Save MS Access tables as CSV
I am new to Python and request your kind assistance. 我是Python的新手,并要求您的帮助。 I have five tables in the MS Access database and I need to compile a CSV file for each of the tables.
MS Access数据库中有五个表,我需要为每个表编译一个CSV文件。 One of the tables is Perm_Reviews , which is part of the snippet.
表之一是Perm_Reviews ,它是代码段的一部分。 Fortunately, I am able to query the MS Access data and it returns rows and the columns associated from the database.
幸运的是,我能够查询MS Access数据,并且它返回数据库中关联的行和列。 Can someone please provide assistance on how to store the tables as CSV files.
有人可以提供有关如何将表格存储为CSV文件的帮助吗?
import pyodbc
import csv
conn_string = ("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=T:\\DataDump\\7.18.2016 PCR etrakit.accdb")
save_csv = 'C:\Desktop\CSVFiles'
conn = pyodbc.connect(conn_string)
cursor = conn.cursor()
SQL = 'select * from Perm_Reviews;'
for row in cursor.execute(SQL):
print row
cursor.close()
conn.close()
print 'All done for now'
I think this is what you are looking for. 我认为这就是您想要的。
import pyodbc
import csv
conn_string = ("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=T:\\DataDump\\7.18.2016 PCR etrakit.accdb")
conn = pyodbc.connect(conn_string)
cursor = conn.cursor()
cursor.execute('select * from Perm_Reviews;')
with open('Perms_Review.csv','w') as f:
writer = csv.writer(f)
writer.writerows([i[0] for i in cursor.description])
writer.writerows(cursor)
cursor.close()
conn.close()
Python has a built-in csv module that you can use readily, below a simple example on csv with headers: Python具有内置的csv模块,您可以随时使用它,下面是带有标头的csv上的一个简单示例:
import csv
with open('names.csv', 'w') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.