我有几个包含特定信息的文本文件。我需要从这些文件中提取所需的信息并将它们放入 MySQL 表中。这些文件包含几行信息,但我只需要这三行,例如:
Name: Gorge
Registration ID: 6657
Registration Time: 2012-09-10 14:31:13
我写了下面的代码,但代码的结果不是我想要的。该代码仍然不包含 SQL 部分的插入。
import fnmatch
import os
import pprint
matches=[]
b=[]
for root, dirnames, filenames in os.walk('d:/Data'):
for filename in fnmatch.filter(filenames, 'Info_reg.txt'):
matches.append(os.path.join(root, filename))
all_keys = ['name','Registration ID','registration time']
for m in matches:
f=open(m,'r')
for line in f:
for n in all_keys:
if line.startswith(n):
a = line.split(':',1)
b.append(a)
代码结果如下所示,我认为无法轻松转换为表格:
['registration time', ' 2012-10-08 17:28:47\n'],
['Registration ID', ' 9876'],
['Name', ' Malcom\n'],
['registration time', ' 2012-10-08 17:28:47\n'],
['Registration ID', ' 45'],
['Name', 'mazu\n'],
有谁知道如何更改我的代码以从该文件中创建一个漂亮的表格?
最佳答案
您想对结果调用 .strip()
,并将整个结果存储在字典中而不是列表列表中。
我们还可以优化行搜索和记录处理;我在这里假设当我们找到一个 Name
条目时,一条新记录已经开始:
records = []
all_keys = {'Name', 'Registration ID', 'registration time'}
first_key = 'Name'
for m in matches:
with open(m, 'r') as f
record = dict.fromkeys(all_keys) # new record dictionary with `None` values
for line in f:
key, value = line.split(':', 1)
key, value = key.strip(), value.strip()
if key not in all_keys:
continue # not interested in this line
if key == first_key and any(v for v in record.itervalues()):
# new record, finalize the previous
records.append(record)
record = dict.fromkeys(all_keys)
record[key] = value
if any(v for v in record.itervalues()):
# there is something in the last record still, add that too
records.append(record)
现在您拥有以下形式的记录列表:
records = [
{'registration time', '2012-10-08 17:28:47', 'Registration ID': '9876', 'Name', 'Malcom'},
{'registration time', '2012-10-08 17:28:47', 'Registration ID': '45', 'Name', 'mazu'},
]
这些可以使用 .executemany()
一次性插入到带有 MySQLdb 的数据库中:
cursor = conn.cursor()
cursor.executemany('INSERT INTO sometable (id, name, time) VALUES (%(Registration ID)s, %(Name)s, %(registration time)s)',
records)
conn.commit()
这会将所有收集到的记录直接插入到数据库中。
关于python - 如何将文本文件的信息放入元组中以转换为 SQL 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16196350/