我有一个制表符分隔的 txt 文件
,其中行由制表符分隔,行由换行符分隔。它实际上是这样的:
476502291\t\tLF3139812164\t\t标题 1\t child 与家庭\nGRAV_2011\t\t完整图片\t独立\n [...等...]
请注意,有时值是由两个制表符而不是一个制表符分隔的。
我需要将其插入到 mysql 表中,这应该会产生以下结果:
ID title genre
476502291 Title 1 Kids & Family
GRAV_2011 The Full Picture Independent
如何读取制表符分隔的 txt 文件并运行 for
循环,以便使用 MySQLdb 将值插入名为 vendor
的表中?
>>> import MySQLdb
>>> conn = MySQLdb.connect (host = "localhost",
user = "me",
passwd = "password",
db = "my-db")
>>> cursor = conn.cursor ()
>>> # for loop # how to read from the txt file to insert it as required?
>>> # cursor.execute (INSERT...)
>>> conn.commit()
>>> conn.close()
最佳答案
第 1 步. 阅读 csv
模块。 http://docs.python.org/library/csv.html 。这就是你想要的。
with open('your_data_file.dat','r') as source:
rdr= csv.reader( source, delimiter='\t', quotechar='')
for row in rdr:
# you have your columns with which to do your insert.
conn.commit()
第 2 步:同时阅读上下文管理器。
from contextlib import closing
with open('your_data_file.dat','r') as source:
rdr= csv.reader( source, delimiter='\t', quotechar='')
with closing(conn.cursor()) as cursor:
for row in rdr:
# you have your columns with which to do your insert.
conn.commit()
这将确保游标和文件正确关闭。
关于python - 将制表符分隔的值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8841205/