1

I'm appreciate to your help in my issue.

I want to append my response query into exist CSV file. I'm implement this by this example but from unknown reason - the output file stay empty.

This is minimal snippet of my code:

import psycopg2
import numpy as np

# Connect to an existing database
conn = psycopg2.connect(dbname="...", user="...", password="...", host="...")
# Open a cursor to perform database operations
cur = conn.cursor()

f = open('file_name.csv', 'ab') # "ab" for appending

cur.execute("""select * from table limit 10""") # I have another query here but it isn't relevant.
cur_out = np.asarray(cur.fetchall())

Until here it works perfect. When I print(cur_out), I got desired output. But in the next step:

np.savetxt(f, cur_out, delimiter=",", fmt='%s')

The file stay empty and I didn't find the reason for that.

Can you help me please?

Thankes for helpers.

fic fic
  • 15
  • 4
  • The accepted answer says they can't reproduce this, can you clarify the situation? – AMC Feb 25 '20 at 16:18
  • Don't know how say that. Probably that existing file interrupt my code run, so the file deleting solved the problem. – fic fic Feb 25 '20 at 17:10

2 Answers2

0
np.savetxt('file_name.csv', cur_out, delimiter=",", fmt='%s')
Aly Hosny
  • 827
  • 5
  • 13
  • This solution doesn't match to the problem. I want to append rows. This answer re-write the whole file. – fic fic Feb 25 '20 at 14:38
  • this what np.savetxt do. you can check https://stackoverflow.com/questions/30376581/save-numpy-array-in-append-mode for appending – Aly Hosny Feb 25 '20 at 14:48
  • @AlyHosny: His approach is good. the open in "a" mode should ignore re-create file. – Yanirmr Feb 25 '20 at 15:00
0

I don't know how to tell you. But your code works for me perfectly.

My suggestions:

  1. If you have existing files in this name, try to delete them and execute your code again,
  2. Try to change the batch size.
  3. Try to change the postfix of the file name to txt or dat.

Best wishes.

fic fic
  • 15
  • 4
Yanirmr
  • 923
  • 8
  • 25
  • @ficfic _It works._ Was it working all along, did one of the suggestions fix it? – AMC Feb 25 '20 at 16:17