Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将多个txt文件加载到mysql中_Python_Mysql - Fatal编程技术网

Python 将多个txt文件加载到mysql中

Python 将多个txt文件加载到mysql中,python,mysql,Python,Mysql,我有40多个txt文件需要加载到Mysql中的一个表中。每个文件包含3列数据,每列列出一种特定类型的数据,但通常每个txt文件的格式完全相同,但这些文件名不同,首先我尝试将数据本地填充'path/*.txt'加载到表xxx中“ 因为我想也许使用*.txt可以让Mysql加载这个文件夹中的所有txt文件。但结果是没有 那么,我如何让Mysql或python做到这一点呢?或者我需要先手动将它们合并到一个文件中,然后使用LOAD DATA LOCAL infle命令 非常感谢!唯一也是最好的方法是将数

我有40多个txt文件需要加载到Mysql中的一个表中。每个文件包含3列数据,每列列出一种特定类型的数据,但通常每个txt文件的格式完全相同,但这些文件名不同,首先我尝试将数据本地填充'path/*.txt'加载到表xxx中“

因为我想也许使用
*.txt
可以让Mysql加载这个文件夹中的所有txt文件。但结果是没有

那么,我如何让Mysql或python做到这一点呢?或者我需要先手动将它们合并到一个文件中,然后使用
LOAD DATA LOCAL infle
命令


非常感谢!

唯一也是最好的方法是将数据合并到一个文件中。使用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()

然后运行您知道的命令(…infle…)将一个文件加载到MySql。只要列之间的分隔严格相同,就可以正常工作。我认为选项卡是最好的;)

如果您想避免合并文本文件,您可以轻松地“扫描”文件夹并对每个文件运行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

你到底想怎么做?所有的东西都在一列的一个字符串中?每个文件的每一个文本都在一个不同的列中?或者有什么不同?你能澄清一下这个问题的区别吗?在我看来,你基本上问的是同一件事…(但我当然可能错了!)同一个问题,同一个用户,没用你试过什么?你的文本文件包含什么?你的数据库模式是什么(例如,你的表是什么?)?抱歉,我没有注意到infle命令只支持一个文件作为输入,所以我想问的是关于合并txt文件的问题,或者Mysql中是否可以使用其他命令。如果您有25个文件,每个文件都有500k+行,这真的是最好的选择吗?将单个巨大文件加载到Mysql中会对性能产生什么影响,我想说nnoDB肯定会在某个时候出现瓶颈和阻塞。。