postgresql 如何在psycopg2中用三列替换fetchall的逗号

zi8p0yeb  于 2023-05-12  发布在  PostgreSQL
关注(0)|答案(1)|浏览(91)

我必须使用fetchall从表中获取3列,我需要将其写入没有逗号的文本文件。

import psycopg2
import pandas as pd
con = psycopg2.connect(database="dbname",user="postgres",password="pwd",host="localhost",port= '5432')
cursor_obj = con.cursor()
sql = f"""SELECT COL1, COL2, COL3 FROM TABLE WHERE COL1= %S, COL3 = 1 ORDER BY COL1,COL2,COL3 ASC;"""
row = cursor_obj.execute(d1,)
resultset = cursor_obj.fetchall()
resultset[len(resultset)] = resultset[len(resultset)].str.replace(',','')

我不得不将no comma col1 col2 col3写入一个文本文件,得到Index错误:列表超出范围。请指导

gk7wooem

gk7wooem1#

而不是使用:resultset[len(resultset)] = resultset[len(resultset)].str.replace(',','')
我修改了你的代码:

list_data = [list(_val) for _val in resultset]
fnl_data = [[str(_val) for _val in _data] for _data in list_data]

之后,您可以打开txt文件并插入这些列表值-

with open("yourtextfile.txt", "w") as f:
    for _val in fnl_data:
        f.write("\t".join(_val) + "\n")

相关问题