2017-02-15 32 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