在Python中制作通用的CSV COPY脚本

时间:2019-07-04 07:48:58

标签: python python-3.x postgresql

我正在使用下面的Python脚本将CSV文件复制到我的PostgreSQL数据库表中。 下面的脚本可以正常工作,但是我正在考虑使此脚本成为通用脚本< / em> ,所以我需要您的建议/建议。

脚本的作用:

1)该脚本将从特定路径中搜索名称为ufl.csv的CSV文件,并将其内容复制到PostgreSQL数据库中的预定义表中。

2)完成复制后,将CSV文件移动到新的目的地。

我要实现的目标:

1)与其预定义诸如ufl.csv之类的文件名,不如获取工作文件夹中的文件(如果可能,还包含其他文件)。

2)我现在已经预定义了表结构(CSV有75列,我可以下载3种不同格式的CSV文件,每种格式具有不同的列号和名称,我想它是一种通用的表,因此无论有多少列或列名如何,都应将CSV数据移植到动态创建的PostgreSQL表中。

请找到以下脚本

import csv
import psycopg2
import time
import os
from datetime import datetime
import shutil
from time import gmtime, strftime

# File path.
filePath='''/Users/local/Downloads/ufl.csv'''
dirName = '/Users/local/Downloads/ufl_old_files/'

try:
  conn = psycopg2.connect(host="localhost", database="postgres", user="postgres",
                         password="postgres", port="5432")
  print('DB connected')

except (Exception, psycopg2.Error) as error:
        # Confirm unsuccessful connection and stop program execution.
        print ("Error while fetching data from PostgreSQL", error)
        print("Database connection unsuccessful.")
        quit()

# Check if the CSV file exists.
#if os.path.isfile(filePath):
 #try:
     #print('Entered loop')   
     #sql = "COPY %s FROM STDIN WITH DELIMITER AS ';'  csv header"
     #file = open(filePath, "r" , encoding="latin-1")
     #table = 'stage.ufl_details'# The table structure is already defined.

if os.path.isfile(filePath):
 try:
     print('Entered loop')   
     #sql = "COPY %s FROM STDIN WITH DELIMITER AS ';'  csv header"
     sql = "COPY %s FROM PROGRAM 'cat /Users/local/Downloads/*' WITH DELIMITER AS ';'  csv header"
     file = open(filePath, "r" , encoding="latin-1")
     table = 'stage.ufl_details'


     with conn.cursor() as cur:
        cur.execute("truncate " + table + ";")
        print('truncated the table')
        cur.copy_expert(sql=sql % table, file=file)
        print('Data loaded')
        conn.commit()
        cur.close()
        conn.close()

 except (Exception, psycopg2.Error) as error:
        print ("Error while fetching data from PostgreSQL", error)
        print("Error adding  information.")
        quit()
#Move the processed CSV file to the new path after renaming it.    

 os.rename(filePath,dirName + 'ufl_old_'+ strftime("%Y_%m_%d", gmtime())+'.csv')

else:
    # Message stating CSV file could not be located.
    print("Could not locate the CSV file.")
    quit()

1 个答案:

答案 0 :(得分:0)

您可以使用done的{​​{1}}选项

FROM PROGRAM