我有超过40个txt文件需要加载到Mysql表中。每个文件包含3列数据,每列列出一种特定类型的数据,但通常每个txt文件的格式是完全相同的,但这些文件名是不同的,首先我尝试LOAD DATA LOCAL INFILE 'path/*.txt' INTO TABLE xxx"
因为我认为也许使用*.txt可以让Mysql加载这个文件夹中的所有txt文件。但事实证明并非如此。
那么我该如何让Mysql或python做到这一点呢?或者我需要先手动将它们合并到一个文件中,然后再使用LOAD DATA LOCAL INFILE命令?
非常感谢!
发布于 2011-11-23 23:54:11
如果希望避免合并文本文件,可以轻松地“扫描”文件夹并为每个文件运行SQL导入查询:
import os
for dirpath, dirsInDirpath, filesInDirPath in os.walk("yourFolderContainingTxtFiles"):
for myfile in filesInDirPath:
sqlQuery = "LOAD DATA INFILE %s INTO TABLE xxxx (col1,col2,...);" % os.path.join(dirpath, myfile)
# execute the query here using your mysql connector.
# I used string formatting to build the query, but you should use the safe placeholders provided by the mysql api instead of %s, to protect against SQL injections发布于 2011-11-23 21:46:23
唯一也是最好的方法是将你的数据合并到一个文件中。使用Python很容易做到这一点:
fout=open("out.txt","a")
# first file:
for line in open("file1.txt"):
fout.write(line)
# now the rest:
for num in range(2,NB_FILES):
f = open("file"+str(num)+".txt")
for line in f:
fout.write(line)
f.close() # not really needed
fout.close()然后运行您知道的命令(...Infile...)将一个文件加载到MySql。只要列之间的间隔完全相同,就可以正常工作。标签页在我看来是最好的;)
https://stackoverflow.com/questions/8243095
复制相似问题