|
| 1 | +import csv,os,xlrd |
| 2 | + |
| 3 | +file_names = ['User','Country','Movie','Language','Topic','Director','Directs'] |
| 4 | + |
| 5 | +def csv_from_excel(): |
| 6 | + wb = xlrd.open_workbook('project-data.xls') |
| 7 | + for item in file_names: |
| 8 | + print item |
| 9 | + file_names_str = str(item) |
| 10 | + sh = wb.sheet_by_name(file_names_str) |
| 11 | + current_csv = open(file_names_str+'.csv', 'wb') |
| 12 | + wr = csv.writer(current_csv, quoting = csv.QUOTE_ALL) |
| 13 | + |
| 14 | + for rownum in xrange(sh.nrows): |
| 15 | + wr.writerow(sh.row_values(rownum)) |
| 16 | + |
| 17 | + current_csv.close() |
| 18 | + |
| 19 | +def RepresentsInt(s): |
| 20 | + try: |
| 21 | + float(s) |
| 22 | + return True |
| 23 | + except ValueError: |
| 24 | + return False |
| 25 | + |
| 26 | +def listToStringWithoutBrackets(list1): |
| 27 | + return str(list1).replace('[','').replace(']','') |
| 28 | + |
| 29 | +def populate(): |
| 30 | + # File should be first emptied before inserting sql code. |
| 31 | + open(item_name+'.sql', 'w').close() |
| 32 | + print'File %s.sql is empty.' % item_name |
| 33 | + |
| 34 | + output_file = open(item_name + '.sql', 'w') |
| 35 | + next(input_file) |
| 36 | + reader = csv.reader(input_file,delimiter=',') |
| 37 | + for row in reader: |
| 38 | + temp = [] |
| 39 | + for item in row: |
| 40 | + if RepresentsInt(item): |
| 41 | + temp.append(int(float(item))) |
| 42 | + else: |
| 43 | + temp.append(str(item)) |
| 44 | + output_file.write( 'INSERT INTO %s \nVALUES (%s);\n' %(item_name,listToStringWithoutBrackets(temp))) |
| 45 | + # print'File %s.sql is populated.' % item_name |
| 46 | + |
| 47 | +csv_from_excel() |
| 48 | +print 'exported data' |
| 49 | +for item in file_names: |
| 50 | + item_name = str(item) |
| 51 | + with open(item_name + '.csv', 'rb') as input_file: |
| 52 | + if not os.path.isfile(item_name + '.sql'): |
| 53 | + populate() |
| 54 | + else: |
| 55 | + if not os.stat(item_name+'.sql').st_size == 0: |
| 56 | + input = (raw_input('There is some data in %s.sql, are you sure to delete your existing data in %s.sql? (y/n)' % (item_name,item_name))) |
| 57 | + if not input =='y' and not input == 'Y': |
| 58 | + print 'Program teminated, user refuse to delete data in %s.sql' % item_name |
| 59 | + break |
| 60 | + else: |
| 61 | + populate() |
| 62 | + else: |
| 63 | + populate() |
0 commit comments