【问题标题】:Use python to import/bulk-load into MS Access使用 python 导入/批量加载到 MS Access
【发布时间】:2019-09-11 02:45:06
【问题描述】:

有谁知道一种使用 python 将多个 CSV 文件加载到一个给定访问表中的简单方法?

例如,我的目录可能有 100 个名为 import_*.csv 的文件(import_1.csv、import_2.csv 等)

MS Access 中有一个目标表应该接收所有这些 csv。

我知道我可以使用 pyodbc 并逐行构建语句来执行此操作,但这需要大量编码。然后,您还必须使 SQL 保持最新,因为可能会添加或删除字段。 MS Access 有它自己的批量加载功能——我希望这可以通过 python 访问,或者 python 有一个库来做同样的事情。

如果有一个图书馆可以像这样简单地做到这一点,我会很棒:

dbobj.connectOdbc(dsn) dbobj.bulkLoad( "MyTable" , "c:/temp/test.csv" )

在内部需要一些工作来确定架构并使其工作。但希望有人已经完成了繁重的工作?

有没有办法进行批量导入?读入 pandas 已经很简单了——但是你必须从那里把它读入 MS Access。

【问题讨论】:

  • 从 pandas 导出到 Access 已在此处显示。 Check this.
  • 泰。这些例子是我不想做的。为了清楚起见,让我编辑我的帖子。

标签: python ms-access bulkinsert


【解决方案1】:

这是一篇旧文章,但我会好好研究一下。因此,您在一个目录中有 100 多个 CSV 文件,并且您希望将所有内容都推送到 MS Access 中。好的,我会在 Python 中将所有 CSV 文件合并到一个 DF 中,然后保存 DF,并将其导入 MS Access。

#1 Use Python to merge all CSV files into one single dataframe:
# Something like...

import pandas as pd
import csv
import glob
import os

#os.chdir("C:\\your_path_here\\")
results = pd.DataFrame([])
filelist = glob.glob("C:\\your_path_here\*.csv")
#dfList=[]
for filename in filelist:
    print(filename)  
    namedf = pd.read_csv(filename, skiprows=0, index_col=0)
    results = results.append(namedf)

results.to_csv('C:\\your_path_here\\Combinefile.csv')

或者,这就是我想要的方式...在 Access 中使用 VBA 将所有 CSV 文件合并到一个表中(对于 Python,无论如何都不需要)。

Private Sub Command1_Click()

    Dim strPathFile As String, strFile As String, strPath As String
    Dim strTable As String
    Dim blnHasFieldNames As Boolean

    ' Change this next line to True if the first row in EXCEL worksheet
    ' has field names
    blnHasFieldNames = False

    ' Replace C:\Documents\ with the real path to the folder that
    ' contains the CSV files
    strPath = "C:\your_path_here\"

    ' Replace tablename with the real name of the table into which
    ' the data are to be imported
    strTable = "tablename"

    strFile = Dir(strPath & "*.csv")
    Do While Len(strFile) > 0
          DoCmd.TransferText acImportDelim, , strTable, strPathFile, True

    ' Uncomment out the next code step if you want to delete the
    ' EXCEL file after it's been imported
    '       Kill strPathFile
    strFile = Dir()
    Loop

End Sub

【讨论】:

  • 我所说的大容量加载是指无需自定义 SQL 编码即可轻松将表导入 Access。我从来没有找到其他方法...
  • 我只是给了你一个方法。你真的试过了吗?我不这么认为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 2013-07-20
相关资源
最近更新 更多