2011-10-22 181 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") 
相關問題