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

2024-04-16 23:51:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我键入以下内容时:

^{pr2}$

我知道了:

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:\联系它,但不起作用。 我第一次成功地运行了它。但不会再有了。 我是个新手,如果我的代码很糟糕,请原谅我。谢谢您。在


Tags: pathnametxtaddoscontactfilewrite