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

2024-06-28 18:52:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有测试结果_分号.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命令(分隔符“;”)将这个.txt文件导入PostgreSQL数据库。COPY命令给我一个错误,因为字段和行都是空的。为了使导入工作正常,我必须在第三行加2个分号,在第四行(空行)加3个分号。如何使用python3.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)  

提前谢谢!你知道吗


Tags: 文件test命令txtaddedpostgresqlcountwith
1条回答
网友
1楼 · 发布于 2024-06-28 18:52:52

我认为你的代码中有一个错误是因为换行。只需这样修改代码:

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

相关问题 更多 >