postgresql 如何重新格式化已经获取的psql查询输出?

sh7euo9m  于 2023-06-05  发布在  PostgreSQL
关注(0)|答案(1)|浏览(174)

我在.txt文件中有默认的psql查询输出,非常难以阅读。任何将其更改为更方便使用的格式的命令或服务(例如CSV)?
我看了文档,但没有找到解决方案。有没有可能,我可以用psql在交互模式下打开它,就像我自己查询一样?

piztneat

piztneat1#

我写了python脚本,没有找到更好的解决方案。

import sys

def convert_to_csv(input_file, output_file):
    with open(input_file, 'r') as inp, open(output_file, 'w') as outp:
        lines = inp.readlines()
        
        # Process header
        buffer = ''
        i = 1  # Skip query line
        while not lines[i].startswith('---'):
            buffer += lines[i].rstrip()
            i += 1

        header = buffer.split('|')
        header = [h.strip() for h in header]
        num_of_columns = len(header)
        outp.write(','.join(header) + '\n')
        
        # Skip separator line(s)
        while lines[i].startswith('---'):
            i += 1

        # Process data rows
        buffer = ''
        for line in lines[i:-1]:  # Skip last line (row count)
            buffer += line.rstrip()
            if buffer.count('|') == num_of_columns - 1:
                row = buffer.split('|')
                row = [f'"{value.strip()}"' if ',' in value.strip() else value.strip() for value in row]
                outp.write(','.join(row) + '\n')
                buffer = ''
        if buffer:  # Ensure last bit of data is written
            row = buffer.split('|')
            row = [f'"{value.strip()}"' if ',' in value.strip() else value.strip() for value in row]
            outp.write(','.join(row) + '\n')

convert_to_csv(sys.argv[1], sys.argv[2])

在终端python3 psql_to_csv.py exp1.txt outp1.csv中运行它。输入文件应以查询命令(如db_name=# select * ...)开头,以(N rows)结尾

相关问题