First ever script (Python) - feedback appreciated
I have just managed to get my first ever script written, in any language
(apart from 'hello world', and other practise scripts!). I've only
self-taught, so I'm sure I've broken many rules, and gone about things in
an inefficient way, so feel free to be critical and suggest how I could
have done it better. It basically does what I want it to do, but the only
unresolved problem I have is that the output.xlsx file has written every
value as [u'Value], and I can't figure out how to write it simply as
Value. Also...I downloaded pyscripter and at the top was:
def main():
pass
if __name__ == '__main__':
main()
and I had no idea what I was supposed to do with that...so I just wrote
below it. Am I supposed to write inside it? Here is my working code...have
at it, and probably have laugh at the same time, at how I've done it! I
really appreciate it...
'''grab the file and declare some variables'''
import xlrd, os.path
data_folder = r"C:\users\hopkinsj\desktop\Python Projects\wus"
filename = r"original.xlsx"
workbook = xlrd.open_workbook(os.path.join(data_folder,filename))
sheet = workbook.sheet_by_index(0)
r = sheet.nrows
i = 1
employees = {}
'''import the employees into the employees dictionary'''
while i < r:
hrid = sheet.row_values(i,0,1)
name = sheet.row_values(i,1,2)
wuid = sheet.row_values(i,2,3)
wuname = sheet.row_values(i,3,4)
wum = sheet.row_values(i,4,5)
parentwuid = sheet.row_values(i,5,6)
employees[i] = hrid, name, wuid, wuname, wum, parentwuid
i += 1
'''put the unique workunits (wuids) as keys in a dictionary, and include
some values.
Where there's' more than one employee assigned to the same wuid, append their
name to the list of names for the given work unit'''
workunits = {}
for k, v in employees.iteritems():
if str(v[2]) not in workunits.keys():
print "Adding to %s to the list of Work Units" % (v[2])
workunits[str(v[2])] = v[3], v[4], v[5], [v[1]]
else:
workunits[str(v[2])][3].append(v[1])
'''put the keys and values of work units dictionary into an excel file'''
import xlwt
output = xlwt.Workbook()
outputsheet = output.add_sheet("output data")
r = 1
for k in workunits:
c = 0
outputsheet.write(r,0,[k])
for val in workunits[k]:
outputsheet.write(r,c+1,str(workunits[k][c]))
c += 1
r += 1
output.save('output.xls')
No comments:
Post a Comment