使用Python从.txt文件填充SQLite3数据库

我正在尝试在django中设置一个网站,该网站允许用户向包含有关其在欧洲议会中的代表的信息的数据库发送查询。我将数据放在逗号分隔的.txt文件中,格式如下:   议会,名称,国家,Party_Group,National_Party,职位      7,Marta Andreasen,英国,欧洲自由民主集团,英国独立党,成员      等等.... 我想用这些数据填充一个SQLite3数据库,但到目前为止我发现的所有教程都只显示了如何手动执行此操作。由于我在文件中有736个观察结果,所以我真的不想这样做。 我怀疑这是一件简单的事情,但如果有人能告诉我如何做到这一点,我将非常感激。 托马斯     
已邀请:
所以假设你的
models.py
看起来像这样:
class Representative(models.Model):
    parliament = models.CharField(max_length=128)
    name = models.CharField(max_length=128)
    country = models.CharField(max_length=128)
    party_group = models.CharField(max_length=128)
    national_party = models.CharField(max_length=128)
    position = models.CharField(max_length=128)
然后,您可以运行
python manage.py shell
并执行以下操作:
import csv
from your_app.models import Representative
# If you're using different field names, change this list accordingly.
# The order must also match the column order in the CSV file.
fields = ['parliament', 'name', 'country', 'party_group', 'national_party', 'position']
for row in csv.reader(open('your_file.csv')):
    Representative.objects.create(**dict(zip(fields, row)))
而且你已经完成了。 附录(编辑) 按照托马斯的要求,这是对
**dict(zip(fields,row))
的解释: 所以最初,
fields
包含我们定义的字段名称列表,
row
包含表示CSV文件中当前行的值列表。
fields = ['parliament', 'name', 'country', ...]
row = ['7', 'Marta Andreasen', 'United Kingdom', ...]
zip()
的作用是将两个列表组合成两个列表中的一对项目列表(如拉链);即
zip(['a','b,'c'], ['A','B','C'])
将返回
[('a','A'), ('b','B'), ('c','C')]
。所以在我们的案例中:
>>> zip(fields, row)
[('parliament', '7'), ('name', 'Marta Andreasen'), ('country', 'United Kingdom'), ...]
dict()
函数只是将对列表转换为字典。
>>> dict(zip(fields, row))
{'parliament': '7', 'name': 'Marta Andreasen', 'country': 'United Kingdom', ...}
**
是一种将字典转换为函数的关键字参数列表的方法。所以
function(**{'key': 'value'})
相当于
function(key='value')
。所以在例子中,调用
create(**dict(zip(field, row)))
相当于:
create(parliament='7', name='Marta Andreasen', country='United Kingdom', ...)
希望这可以解决问题。     
正如SiggyF所说,与Joschua略有不同: 使用您的架构创建一个文本文件,例如: CREATE TABLE政治家(     议会文本,     姓名文字,     国家文字,     Party_Group文字,     National_Party文字,     定位文字 ); 创建表格:
>>> import csv, sqlite3
>>> conn = sqlite3.connect('my.db')
>>> c = conn.cursor()
>>> with open('myschema.sql') as f:            # read in schema file 
...   schema = f.read()
... 
>>> c.execute(schema)                          # create table per schema 
<sqlite3.Cursor object at 0x1392f50>
>>> conn.commit()                              # commit table creation
使用csv模块读取要插入的数据的文件:
>>> csv_reader = csv.reader(open('myfile.txt'), skipinitialspace=True)
>>> csv_reader.next()                          # skip the first line in the file
['Parliament', 'Name', 'Country', ...

# put all data in a tuple
# edit: decoding from utf-8 file to unicode
>>> to_db = tuple([i.decode('utf-8') for i in line] for line in csv_reader)
>>> to_db                                      # this will be inserted into table
[(u'7', u'Marta Andreasen', u'United Kingdom', ...
插入数据:
>>> c.executemany("INSERT INTO politicians VALUES (?,?,?,?,?,?);", to_db)
<sqlite3.Cursor object at 0x1392f50>
>>> conn.commit()
验证所有内容是否符合预期:
>>> c.execute('SELECT * FROM politicians').fetchall()
[(u'7', u'Marta Andreasen', u'United Kingdom', ...
编辑: 既然你已经在输入上解码(到unicode),你需要确保在输出上进行编码。 例如:
with open('encoded_output.txt', 'w') as f:
  for row in c.execute('SELECT * FROM politicians').fetchall():
    for col in row:
      f.write(col.encode('utf-8'))
      f.write('n')
    
您可以使用csv模块读取数据。然后你可以创建一个insert sql语句并使用executemany方法:
  cursor.executemany(sql, rows)
或者如果使用sqlalchemy,请使用add_all。     
你问创建(** dict(zip(fields,row)))行是做什么的。 我不知道如何直接回复你的评论,所以我会在这里试着回答。 zip将多个列表作为args并返回其对应元素的列表作为元组。 zip(list1,list2)=> [(list1 [0],list2 [0]),(list1 [1],list2 [1]),....] dict获取一个2元素元组的列表,并返回一个字典,将每个元组的第一个元素(键)映射到它的第二个元素(值)。 create是一个接受关键字参数的函数。您可以使用** some_dictionary将该字典作为关键字参数传递给函数。 create(** {'name':'john','age':5})=> create(name ='john',age = 5)     
以下内容应该有效:(未经测试)
# Open database (will be created if not exists)
conn = sqlite3.connect('/path/to/your_file.db')

c = conn.cursor()

# Create table
c.execute('''create table representatives
(parliament text, name text, country text, party_group text, national_party text, position text)''')

f = open("thefile.txt")
for i in f.readlines():
    # Insert a row of data
    c.execute("""insert into representatives
                 values (?,?,?,?,?,?)""", *i.split(", ")) # *i.split(", ") does unpack the list as arguments

# Save (commit) the changes
conn.commit()

# We can also close the cursor if we are done with it
c.close()
    

要回复问题请先登录注册