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!")

When I type this:

add('jack','222','ds@gmail.com')

I got this:

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'

I have tried E:\Contact it stil does not work. And I have ran it successfully for the first time. But no more. I am a newbie forgive me if my code sucks. Thank you.

Evan
  • 335
  • 1
  • 3
  • 11

1 Answers1

3

If the path does not exist, the os.path.exists call returns False rather than throwing an exception. So the first part of the code do not work as intended. Use this instead

if not os.path.exists("E:/Contact"):
    os.mkdir("E:/Contact")  
Wai Yip Tung
  • 18,106
  • 10
  • 43
  • 47