用于使用Python导入PostgreSQL的Perpare.txt文件

用于使用Python导入PostgreSQL的Perpare.txt文件,python,postgresql,Python,Postgresql,我有test\result\u wo\u分号.txt文件: 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复制命令(分隔符“;”)将此.txt文件导入PostgreSQL数据库。COPY命

我有test\result\u wo\u分号.txt文件:

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复制命令(分隔符“;”)将此.txt文件导入PostgreSQL数据库。COPY命令给我一个错误,因为字段和行都是空的。要使导入工作正常,我必须在第三行添加2个分号,在第四行(空行)添加3个分号。如何使用Python 3.5实现这一点。(我正在使用Windows7)。到目前为止我编写的代码:

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)  
打开('test\\result\u wo\u分号.txt','r')作为o:
对于o中的行:
分号_count=line.count(“;”)

如果分号计数我认为您的代码中有一个错误,因为换行符。只需按如下方式修改代码:

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')  
打开('test\\result\u wo\u分号.txt','r')作为o:
对于o中的原始_线:
线条=原始线条。线条()
分号_count=line.count(“;”)
如果分号_计数<3:
添加了_分号=';'*(3-分号(u count)#这里有点不对劲
将open('test\\result_added_分号.txt','a')作为t:
t、 写入(行+添加了\u分号+'\n')