Advertisement
Guest User

Untitled

a guest
Oct 31st, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. import psycopg2
  2. import sys
  3. from os import listdir
  4. from os.path import isfile, join
  5. import csv
  6. import re
  7. import io
  8.  
  9. try:
  10. con = db_connect("dbname = '[redacted]' user = '[redacted]' password = '[redacted]' host = '[redacted]'")
  11. except:
  12. print("Can't connect to database.")
  13. sys.exit(1)
  14. cur = con.cursor()
  15.  
  16. upload_file = io.StringIO()
  17.  
  18. file_list = [f for f in listdir(mypath) if isfile(join(mypath, f))]
  19. for file in file_list:
  20. id_match = re.search(r'.*-(d+).csv', file)
  21. if id_match:
  22. id = id_match.group(1)
  23. file_name = format(id_match.group())
  24. with open(mypath+file_name) as fh:
  25. id_reader = csv.reader(fh)
  26. next(id_reader, None) # Skip the header row
  27. for row in id_reader:
  28. [stuff goes here to get desired values from file]
  29. if upload_file.getvalue() != '': upload_file.write('n')
  30. upload_file.write('{0}t{1}t{2}'.format(id, [val1], [val2]))
  31.  
  32. print(upload_file.getvalue()) # prints output that looks like I expect it to
  33. # with thousands of rows that seem to have the right values in the right fields
  34.  
  35. cur.copy_from(upload_file, '[my_table]', sep='t', columns=('id', 'col_1', 'col_2'))
  36. con.commit()
  37.  
  38. if con:
  39. con.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement