在python中删除文件时出错
我正试图写一个基本的数据库管理程序 代码如下所示:在python中删除文件时出错,python,database,Python,Database,我正试图写一个基本的数据库管理程序 代码如下所示: 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
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)
当我试图删除文件“EMP.txt”时,问题出现在delete函数的部分
它给出了一个错误:
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'C:/EMP.txt'
有什么解决办法吗?问题似乎是您要打开文件EMP.txt两次
我认为无需在删除功能中重新打开文件,或在重新打开文件之前尝试关闭文件。Sunny是正确的,但他的解决方案缺少一个元素 即使无法打开文件,您仍将继续执行
while
循环。这就是为什么会出现第一个错误,即赋值前的引用。只有在没有异常的情况下,才需要执行while
循环。有很多方法可以做到这一点,但我会采用这种方法:
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:
# ...
您还可以在进入try之前设置fp=None
,然后在while
循环之前检查fp==None
一般来说,我不会使用
global
,它的效果有几个含义。另外,我不明白为什么你要在循环的每一次迭代中重新定义你的函数,也不理解为什么你<代码>导入OS两次,但是我会考虑在循环之外定义这些函数。将fp
作为参数传递给他们。在尝试重新打开文件处理程序之前,似乎没有正确关闭文件处理程序,这可能是问题的根源。在处理文件时,尝试使用with
构造来避免这种情况,因为您在一个类中,所以应该将fp
作为该类的一个属性,因此在创建self.fp
之前添加self
。这意味着您的所有函数都将有权访问同一个对象(当前没有)@wnn由于他的代码不在类中,他在编写模块级代码之前刚刚定义了一个类。当我没有在delete()中重新打开文件fp时,它在第行给出错误:“fp.seek(0,os.seek_SET)”错误:分配前引用了局部变量“fp”。请尝试在删除函数的顶部添加全局fp
。现在,它在操作系统上出现错误。重命名语句:WindowsError:[error 5]访问被拒绝这似乎是另一个问题。请检查您是否能够以非编程方式重命名c:drive中的文件。可能与权限有关。有没有办法只打开文件而不给出其完整位置?