首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用Python制作一个通用的CSV复制脚本

用Python制作一个通用的CSV复制脚本
EN

Stack Overflow用户
提问于 2019-07-04 07:48:58
回答 1查看 49关注 0票数 0

我正在使用下面的Python将一个CSV文件复制到我的PostgreSQL数据库表中。下面的脚本运行良好,但是我想让这个脚本成为一个通用的,所以我需要您关于如何这样做的建议/建议。

脚本做什么:

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

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

我想要达到的目标:

1)不要预先定义文件名(如ufl.csv ),而是接受工作文件夹中的文件(如果可能的话,使用al文件)。

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

请找到下面的脚本,

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-04 08:21:45

您可以使用FROM PROGRAM选项的COPY

代码语言:javascript
复制
COPY tablename FROM PROGRAM 
     'cat /Users/local/Downloads/ufl_old_files/*'  WITH DELIMITER AS ';'  csv header
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56883069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档