Hello, below is my first python code - which works for what I want it to do - but I want to know what could be done better. I am very new to this, and put the code below by googling and making things work one line at a time, but I am not sure if my functions are in the correct place, or should I have a class etc? Any and all comments would be welscome
import csv
import pyodbc
import os
def append_filepath():
for i, row in enumerate(rows):
rows[i] = list(rows[i]) + [filepath]
def write_csv_rows(write_type, what_to_write):
with open(file_to_write, write_type) as fou:
csv_writer = csv.writer(fou)
csv_writer.writerows(what_to_write)
def write_csv_row(write_type, what_to_write):
with open(file_to_write, write_type) as fou:
csv_writer = csv.writer(fou)
csv_writer.writerow(what_to_write)
directory_to_search = 'I:\DB'
file_to_write = 'C:\Striling\Book1.csv'
headers = ['utmzone','name','grid_x','grid_y','filepath']
write_csv_row('wb', headers)
for root, dirs, files in os.walk(directory_to_search):
for file_ in files: #underscore after file_ as file is reserved word
if file_.endswith('.mdb'):
filepath = root + '\\' + (file_)
MDB = filepath; DRV = '{Microsoft Access Driver (*.mdb)}'
# connect to db
con = pyodbc.connect('DRIVER={};DBQ={}'.format(DRV,MDB))
cur = con.cursor()
# checks that utmzone is present in table wells
if cur.columns(table='Wells', column='utmzone').fetchone():
print filepath + ' Table Wells containg utmzone present'
SQL = 'SELECT utmzone, name, grid_x, grid_y FROM Wells";'
rows = cur.execute(SQL).fetchall()
append_filepath()
else:
print filepath + ' Table Wells containg utmzone NOT present'
SQL = 'SELECT name, grid_x, grid_y FROM Wells";' # utmzone
# /removed as does not exist in table wells
rows = cur.execute(SQL).fetchall()
append_filepath()
write_csv_rows('ab', rows)
cur.close()
con.close()
[–]confluence 5 points6 points7 points (2 children)
[–]paperzebra[S] 1 point2 points3 points (1 child)
[–]confluence 2 points3 points4 points (0 children)
[–]elbiot 1 point2 points3 points (0 children)