IOError: [Errno 2] 没有这样的文件或目录:

2 投票
1 回答
4669 浏览
提问于 2025-04-17 04:49
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:\Contact,但还是不行。 我第一次运行成功了,但之后就不行了。 我还是个新手,如果我的代码不好请多多包涵。谢谢。

1 个回答

3

如果路径不存在,os.path.exists 这个函数会返回 False,而不是抛出一个错误。所以代码的第一部分没有按预期工作。可以用下面这个来替代。

if not os.path.exists("E:/Contact"):
    os.mkdir("E:/Contact")  

撰写回答