database - Error in Removing a file in python -
i trying write program elementary database management.
the code provided below:
class emp(): def __init__(self,**kwds): self.__dict__.update(kwds) e=emp() try: fp=open('c:/emp.txt','rb+') # open file reading except: try: fp=open('c:/emp.txt','wb+') # open file writing except: print 'cannot open file' while 1: print "1.add records" print "2.list records" print "3.modify records" print "4.delete records" print "0.exit" print "your choice" choice=eval(raw_input()) def add(): import os fp.seek(0,os.seek_end) another='y' while another=='y': print "\nenter name,age , basic salary:" e.name=raw_input() e.age=eval(raw_input()) e.bs=eval(raw_input()) ch="%s %d %f" % (e.name,e.age,e.bs) fp.writelines("\n") fp.writelines(ch) print "add record(y/n)" another=raw_input() def list(): import os fp.seek(0,os.seek_set) line in fp: # iterate on each line e.name, e.age, e.bs = line.split() # split whitespace e.age = int(e.age) # convert age string int e.bs = float(e.bs) # convert bs string float print "%s %d %f\n" %(e.name, e.age, e.bs) def modify(): another='y' while another=='y': print "\nenter name of employee modify" empname=raw_input() import os fp.seek(0,os.seek_set) line in fp: e.name, e.age, e.bs=line.split() e.age = int(e.age) # convert age string int e.bs = float(e.bs) if(cmp(e.name,empname)==0): print "\nenter new name,age & bs" e.name=raw_input() e.age=eval(raw_input()) e.bs=eval(raw_input()) fp.seek(-len(line),os.seek_cur) ch="%s %d %f" % (e.name,e.age,e.bs) fp.writelines(ch) break print "\nmodify record(y/n)" another=raw_input() def delete(): another='y' while another=='y': print "\nenter name of employee delete" empname=raw_input() ft=open('c:/temp.txt','wb') fp=open('c:/emp.txt','rb+') import os fp.seek(0,os.seek_set) line in fp: e.name, e.age, e.bs=line.split() e.age = int(e.age) # convert age string int e.bs = float(e.bs) if(cmp(e.name,empname)!=0): ch="%s %d %f" % (e.name,e.age,e.bs) ft.writelines(ch) ft.writelines("\n") fp.close() ft.close() import os os.remove("c:/emp.txt") # delete file emp.txt os.rename( "c:/temp.txt", "c:/emp.txt" ) # rename file temp.txt emp.txt fp=open('c:/emp.txt','rb+') print "delete record(y/n)" another=raw_input() def exit(): import sys fp.close() sys.exit(0) def switch(c): return {1: add, 2: list, 3: modify, 4: delete, 0: exit, }[c]() switch(choice)
the problem coming in segment of delete function when trying remove file "emp.txt"...
it giving error:
windowserror: [error 32] process cannot access file because being used process: 'c:/emp.txt'
any solution this?
the issue seems opening file emp.txt twice.
i think there no need re-open file in delete function, or try closing file before reopening it.
Comments
Post a Comment