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])
1条答案
按热度按时间piztneat1#
我写了python脚本,没有找到更好的解决方案。
在终端
python3 psql_to_csv.py exp1.txt outp1.csv
中运行它。输入文件应以查询命令(如db_name=# select * ...
)开头,以(N rows)
结尾