import os
try:
os.path.exists("E:/Contact") #Check if dir exist
except:
os.mkdir("E:/Contact") #if not, create
def add(name,cell,email): #add contact
conPath0 = 'E:/Contact'
conPath1 = '/ '
conPath1b = conPath1.strip()
conPath2 = name+'.txt'
conPath = conPath0+conPath1b+conPath2
file = open(conPath,'w')
file.write('Name:'+ name+'\n') #write into file
file.write('Cell:'+ cell+'\n')
file.write('Email:'+ email+'\n')
file.close()
def get(name): #get contact
conPath0 = 'E:/Contact'
conPath1 = '/ '
conPath1b = conPath1.strip()
conPath2 = name+'.txt'
conPath = conPath0 + conPath1b + conPath2
try:
os.path.exists(conPath) #check if exist
file = open(conPath,'r')
getFile = file.readlines()
print(getFile)
except:
print("Not Found!")
def delete(name): #delete contact
conPath0 = 'E:/Contact'
conPath1 = '/ '
conPath1b = conPath1.strip()
conPath2 = name+'.txt'
conPath = conPath0 + conPath1b + conPath2
try:
os.path.exists(conPath)
os.remove(conPath)
print(name+"has been deleted!")
except:
print("Not Found!")
当我输入时:
add('jack','222','ds@gmail.com')
我明白了:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
add('jack','222','ds@gmail.com')
File "E:/lab/t.py", line 13, in add
file = open(conPath,'w')
IOError: [Errno 2] No such file or directory: 'E:/Contact/jack.txt'
我试过E:\联系它stil不起作用。 我第一次成功地运行了它。但没有更多。 如果我的代码很糟糕,我是新手,请原谅我。谢谢。
答案 0 :(得分:3)
如果路径不存在,则os.path.exists调用返回False而不是抛出异常。因此代码的第一部分不能按预期工作。请改用
if not os.path.exists("E:/Contact"):
os.mkdir("E:/Contact")