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

时间:2015-12-13 18:32:22

标签: python postgresql

我有test \ result_wo_semicolon.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 COPY命令(delimiter';')将此.txt文件导入PostgreSQL数据库。 COPY命令因空字段和空行而给出错误。要进行导入工作,我必须在第三行添加2个分号,在第4行添加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)  

提前谢谢!

1 个答案:

答案 0 :(得分:0)

我认为由于换行符,您的代码中存在错误。只需像这样修改你的代码:

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')