【问题标题】:Exporting tables to CSV on postgres without having to use 'Text to columns'在 postgres 上将表导出为 CSV,而无需使用“文本到列”
【发布时间】:2016-04-20 13:53:13
【问题描述】:

我一直在使用以下脚本从 redshift 和 postgres 导出表:

@export on;
@export set filename="D:\Users\files\filename.csv" CsvColumnDelimiter=";";
SELECT * FROM schemaname.tablename;
@export off;

这很好用,但要在单独的列中获取数据,我必须使用 excel 中的“文本到列”功能。我正在寻找一个可以自动执行“文本到列”步骤的脚本,因为我有 700 多个表。我一直在寻找可以执行此操作的 SQL 和 Python 脚本,但到目前为止还没有找到任何东西。

【问题讨论】:

    标签: python sql excel csv


    【解决方案1】:

    Excel 需要在 CSV 中使用逗号分隔符。您需要更改分隔符,或更改 Excel 的默认分隔符。您可以在 Region & Language 设置中执行此操作。

    【讨论】:

      【解决方案2】:

      python 有一个内置的 csv 模块。

      import csv
      with open('in.csv', 'r') as infp:
          with open('out.csv', 'w') as outfp:
              reader = csv.reader(infp, delimiter=';')
              writer = csv.writer(outfp, delimiter=',')
              for row in reader:
                  writer.writenow(row)
      

      应该翻译分隔符。详情请查看CSV

      可能有更好的方法来做到这一点。在 Linux 上,有 sed、awk、tr 等可以在一条神秘的行中做到这一点。见 8 examples to change the delimiter of a file in Linux。但我不知道 Windows 等价物,如果有的话。

      【讨论】:

        猜你喜欢
        • 2014-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-06
        • 1970-01-01
        • 1970-01-01
        • 2021-02-06
        相关资源
        最近更新 更多