2017-02-15 35 views
0

我有一个包含一定量的格式小时HH:MM'的文本文件,以便这样的下方,:的Python:从.txt文件到SQL表

Times1.txt:

10:12 13:22 15:45 18:23 19:20(...) 

现在我想用Python和sqlite3的导入此.txt文件名为Times1.db SQL数据库,并创建一个表,一列,这列各行会在下一个小时,这样的:

10:12 
13:22 
15:45 
18:23 
19:20 
(...) 

所以我可以从这张表中得到例如只有第二行,这将是13:22。

如果这可能会改变一些.txt文件可以存储这个时间以这种格式,以及:

10:12,12:22,15:45,(...) 

10:12 
12:22 
15:45 
(...) 

我试图做到这一点在很多方面,但所有我能得到是所有小时的单行。

这是我尝试过了这么远:

import os 
import sqlite3 

conn = sqlite3.connect('test.db') 
c = conn.cursor() 

#c.execute("CREATE TABLE time(hour REAL)") 
#table time is already created 

#thanks to @Asav Patel 
with open('test.txt') as f1: 
    hours = next(f1).split() 

for hour in hours: 
    print (hour)  

c.executemany("INSERT INTO time (hour) VALUES (?)", (hour,)) 

conn.commit() 

def read_from_database(): 
    sql = "SELECT * FROM time" 

    for row in c.execute(sql): 
     print(row) 
     print(row[0]) 

read_from_database() 

conn.close() 
+0

我可以看你,你做了什么这么远吗? – orvi

+0

@orvi我发布了我到目前为止 – Gewof

回答

0

假设有只有一个文件一行。

with open('test_docs/file1.txt') as f: 
    hours = f.read().split() 

for hour in hours: 
    print (hour) 
+0

嗨,感谢您的重播。这是行得通的,但是我怎样才能将这个分割文本导入到SQL数据库中,这样每个小时都能在列中创建一个新行? – Gewof

+0

您必须每小时生成一条SQL语句并将其写入另一个文件,然后在数据库中导入该文件 –

-1

好吧,我发现了一种方法来做到这一点:)我测试了它,它的工作。

import sqlite3 

conn = sqlite3.connect('test.db') 
c = conn.cursor() 

c.execute("CREATE TABLE example(Time REAL)") 

num_lines = sum(1 for line in open('test.txt')) 
f=open('test.txt') 
lines=f.readlines() 
i=1 
while True: 
    time = (lines[i]) 
    c.execute("INSERT INTO example (Time) VALUES (?)", (time,)) 
    conn.commit() 
    i+=1 
    if i == num_lines: 
     break 

conn.close() 

@cwallenpoole

但这仅仅是我发现创建这样的表方式: table

+1

您正在多次读取整个文件。 – cwallenpoole

+0

@cwallenpoole你知道更好的方式来创建一个表,就像我在上面的评论中发布的那样吗? – Gewof