2011-10-22 182 views
2
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!") 

当我键入:IO错误:[错误2]没有这样的文件或目录:

add('jack','222','[email protected]') 

我得到这个:

Traceback (most recent call last): 
    File "<pyshell#0>", line 1, in <module> 
    add('jack','222','[email protected]') 
    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联系它不起作用。 而且我第一次成功运行它。但没有更多。 我是一个新手原谅我,如果我的代码糟透了。谢谢。

回答

3

如果路径不存在,os.path.exists调用返回False而不是抛出异常。所以代码的第一部分不能按预期工作。改用

if not os.path.exists("E:/Contact"): 
    os.mkdir("E:/Contact") 
相关问题