Python将CSV文件数据导入PostgreSQL中。

问题描述 投票:0回答:1

我们要使用Python psycopg2模块输入CSV文件数据。如果我的代码将CSV文件中的单元格数据改为None,该怎么办?

import psycopg2
from datetime import datetime

datetime.now().month, datetime.now().day, datetime.now().hour, datetime.now().minute,datetime.now().second))
conn_string= "host='' dbname='' user='' password='' "
conn=psycopg2.connect(conn_string)
curs = conn.cursor()
f = open(r'output.csv', 'r')
curs.copy_from(f,'temp',sep=',',null='None' )
f.close()
conn.close()
datetime.now().month, datetime.now().day, datetime.now().hour, datetime.now().minute,datetime.now().second))
print("CSV file import done.")
python csv psycopg2
1个回答
0
投票
import psycopg2
import csv
import io
from datetime import datetime

print ("시작 시간 %s년 %s월 %s일 %s시 %s분 %s초 " %(datetime.now().year, datetime.now().month, datetime.now().day, datetime.now().hour, datetime.now().minute,datetime.now().second))
conn_string = "host='' dbname='' user='' password='' "
conn = psycopg2.connect(conn_string)
cur = conn.cursor()

# Use the COPY function on the SQL we created above.
SQL_for_file_output = "COPY ({0}) TO STDOUT WITH CSV ".format("select * from sk_ds_service_age_p_202001")
# Set up a variable to store our file path and name.
t_path_n_file = "output.csv"
with open(t_path_n_file, 'w') as f_output:
    cur.copy_expert(SQL_for_file_output, f_output)
print ("종료 시간 %s년 %s월 %s일 %s시 %s분 %s초 " %(datetime.now().year, datetime.now().month, datetime.now().day, datetime.now().hour, datetime.now().minute,datetime.now().second))
print("CSV file export done.")
© www.soinside.com 2019 - 2024. All rights reserved.