如何使用Python将空格分隔的文本文件插入mysql?
我的文本文件如下所示:如何使用Python将空格分隔的文本文件插入mysql?,python,mysql,parsing,Python,Mysql,Parsing,我的文本文件如下所示: 10May2013 3.1 http://ncbi.org p.sojae_aafeatureimp p.sojae_aafeatureimp 10May2013 3.2 http://ncbi.org p.sojae_aasequenceimp p.sojae_aasequenceimp 10May2013 3.3 http://ncbi.org p.sojae_blatalignment p.sojae_blatali
10May2013 3.1 http://ncbi.org p.sojae_aafeatureimp p.sojae_aafeatureimp
10May2013 3.2 http://ncbi.org p.sojae_aasequenceimp p.sojae_aasequenceimp
10May2013 3.3 http://ncbi.org p.sojae_blatalignment p.sojae_blatalignment
如何解析这些单独的行并将其插入数据库
数据库结构:(日期、版本、url、名称、描述)
我必须使用Python将文本文件中的值插入mysql。到目前为止,我的脚本如下所示:
import MySQLdb, csv, sys
with open('externaldatabase.txt') as textfile:
csvreader = csv.reader(textfile)
csvdata = []
for row in csvreader:
csvdata.append(row)
conn = MySQLdb.connect (host = "localhost",user = "username", passwd = "password",db = "database_name")
c = conn.cursor()
for row in csvdata:
# Insert a row of data
c.execute("INSERT INTO externaldatabase (release_date, version, download_url, name, description) VALUES ('%s', '%s', '%s', '%s', '%s')" % (row))
conn.commit()
c.close()
但这让我犯了一个错误:
Traceback (most recent call last):
File "csv1.py", line 16, in <module>
c.execute("INSERT INTO externaldatabase (release_date, version, download_url, name, description) VALUES ('%s', '%s', '%s', '%s', '%s')" % (row))
TypeError: not enough arguments for format string
回溯(最近一次呼叫最后一次):
文件“csv1.py”,第16行,在
c、 执行(“插入外部数据库(发布日期、版本、下载url、名称、描述)值(“%s”、“s”、“s”、“s”、“s”)”)”%(行))
TypeError:格式字符串的参数不足
您需要将分隔符设置为csv。读卡器功能:
csvreader = csv.reader(textfile, delimiter='\t')
您没有在代码中这样做,因此Python不会分割CSV文件的行。这就是它给出错误的原因
如果您有包含MySQL表所有列的文件,那么可以使用 指挥部。它比一行一行地装载快得多
LOAD DATA INFILE 'externaldatabase.txt'
INTO TABLE database_name.externaldatabase
FIELDS TERMINATED BY '\t';
这不是一个人们为你做事的论坛。做出一些努力。你尝试了什么?请再次查看我的帖子。我发布了到目前为止我所做的编码。我是一个新手,但必须完成这个。任何帮助都将不胜感激。