2015-12-13 69 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')