Error in Removing a file in python

I am trying to write a program for elementary database management.

The code is provided below:

class emp():
    def __init__(self,**kwds):
        self.__dict__.update(kwds)
e=emp()
try:
    fp=open('C:/EMP.txt','rb+')                             # open the file for reading
except:
    try:
        fp=open('C:/EMP.txt','wb+')                             # open the file for 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 and 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 another record(Y/N)"
            another=raw_input()
    def list():
        import os
        fp.seek(0,os.SEEK_SET)
        for line in fp:                                        # iterate over each line
            e.name, e.age, e.bs = line.split()                     # split it by whitespace
            e.age = int(e.age)                                     # convert age from string to int
            e.bs = float(e.bs)                                     # convert bs from string to float
            print "%s %d %f\n" %(e.name, e.age, e.bs)
    def modify():
        another='Y'
        while another=='Y':
            print "\nEnter name of employee to modify"
            empname=raw_input()
            import os
            fp.seek(0,os.SEEK_SET)
            for line in fp:
                e.name, e.age, e.bs=line.split()
                e.age = int(e.age)                                     # convert age from string to 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 another Record(Y/N)"
            another=raw_input()
    def delete():
        another='Y'
        while another=='Y':
            print "\nEnter name of employee to delete"
            empname=raw_input()
            ft=open('C:/TEMP.txt','wb')
            fp=open('C:/EMP.txt','rb+')
            import os
            fp.seek(0,os.SEEK_SET)
            for line in fp:
                e.name, e.age, e.bs=line.split()
                e.age = int(e.age)                                     # convert age from string to 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 a file from TEMP.txt to EMP.txt
            fp=open('C:/EMP.txt','rb+')
            print "Delete another 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 is coming in the segment of delete function when i am trying to remove the file "EMP.txt"...

It is giving an error:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'C:/EMP.txt'

Any solution for this?

Answers


The issue seems to be that you are opening the file EMP.txt twice.

I think there is no need to re-open the file in the delete function, or Try closing the file before reopening it.


Sunny is correct, but there is a missing element to his solution.

You are continuing on to the while loop even if you cannot open the file. That is why you are getting the first error, the reference before assignment. You need to make the while loop only occur if you do not have an exception. There are many ways to do this, but I would take this approach:

try:
    fp=open('C:/EMP.txt','rb+')                             # open the file for reading
except Exception as e:
    try:
        fp=open('C:/EMP.txt','wb+')                             # open the file for writing
    except Exception as e:
        print 'cannot open file'
        raise    # or you could return here instead - depends on what you want
while:
    # ...

You could also set fp = None before you enter the try, and then before your while loop check for whether fp == None.

I would not use global in general, it has several implications in its effects. Also, I do not understand why you are redefining your functions every iteration of the loop, nor do I understand why you import os twice, but I would consider defining these functions outside of the loop, passing fp as an argument to them instead.


Need Your Help

element replacement in grid unit vector

r r-grid

I've been baffled by this a few times already, so here's a made-up question for others who might stumble upon the same problem.

Simplest way to empty a database with ForeignKeys without deleting/creating it

php mysql database

I would like to empty a Mysql database (eg destroy all tables) . But: I don't have the permission to delete that database. So I can't use the trick