1

I have a COPY command in psycopg2 which I am running in a loop. I wanted to know how can I append to CSV rather than performing fresh copy everytime.

code:

while True:

    cur.execute("COPY (SELECT id,a,b,c,d from t1,t2 WHERE date>= TIMESTAMP TIMESTAMP %(t)s AND date < TIMESTAMP %(t)s + interval '1h' * t2.frequency) \
           TO 'path/to/file.csv' DELIMITER ',' CSV;", d)

Thanks in advance.

6
  • Could you update your question with the section of code in question? See stackoverflow.com/help/mcve and stackoverflow.com/help/how-to-ask Commented Jun 16, 2016 at 14:57
  • Updated the question. It's a pretty generic question of appending to csv file when copy command is being used in a loop. Commented Jun 16, 2016 at 15:05
  • I don't recall COPY being able to append; however, since you are already using Python, why not just combine all the outputs into a single file after? Commented Jun 16, 2016 at 15:19
  • Do you mean opening the file in append mode and then applying the "Copy" command? Commented Jun 16, 2016 at 15:26
  • No. COPY each individual file then concatenate them into one file using Python. Commented Jun 16, 2016 at 15:58

1 Answer 1

4

This is an ugly hack (only works on unix)

COPY table_one(id)
TO PROGRAM 'cat - >/tmp/onetwo.out'
        ;

COPY table_two(id)
TO PROGRAM 'cat - >>/tmp/onetwo.out'
        ;
Sign up to request clarification or add additional context in comments.

3 Comments

I didn't try this. What does it do? Can you explain it? I understand that the filename's path is /tmp/onetwo.out. Why do you have single > in first line and >> in second line?
postgresql.org/docs/9.5/static/sql-copy.html The copy command can read/write from/to a program's stdout/stdin, instead of a file. (This assumes unix, I don't know if windows has usable pipes yet)
The > redirects a program's output to a file. The >> does too, but appends to the file. The cat - program simply copies it's stdin to stdout.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.