2015-12-13 71 views
0

我有測試\ result_wo_semicolon.txt文件:Perpare .txt文件PostgreSQL的導入與Python

date;time;CO2;CH4 
2012-03-29;20:13:20.464;6.2990027157E+002;1.1734711917E-001 
2012-03-29;20:54:49.510 

2012-03-29;20:55:40.511;-2.6541031080E-001;4.1844418258E-003 

我想導入PostgreSQL的COPY命令此.txt文件到PostgreSQL數據庫(分隔符 ';')。由於空字段和空行,COPY命令給我一個錯誤。爲了使導入工作,我必須添加2分號到第三行和3分號到第四行(空行)。我如何用Python 3.5實現這一點。 (我正在使用Windows 7)。我寫的代碼迄今爲止:

with open('test\\result_wo_semicolon.txt','r')as o: 
for line in o: 
    semicolon_count=line.count(';') 
    if semicolon_count<3: 
     added_semicolons=';'*(int(3)-int(semicolon_count))#there is something wrong here 
     with open ('test\\result_added_semicolons.txt','a')as t: 
      t.write(line+added_semicolons) 

提前致謝!

回答

0

我想你的代碼中有一個bug,因爲換行符。只需修改您的代碼,如下所示:

with open('test\\result_wo_semicolon.txt','r')as o: 
    for raw_line in o: 
    line = raw_line.strip() 
    semicolon_count = line.count(';') 
    if semicolon_count < 3: 
     added_semicolons= ';' * (3 - semicolon_count) # there is something wrong here 
     with open ('test\\result_added_semicolons.txt','a')as t: 
     t.write(line + added_semicolons + '\n')