【问题标题】:IOError: [Errno 2] No such file or directory:IOError: [Errno 2] 没有这样的文件或目录:
【发布时间】:2011-10-23 00:27:17
【问题描述】:
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 还是不行。 我第一次成功运行它。但没有了。 如果我的代码很糟糕,我是新手请原谅我。谢谢。

【问题讨论】:

    标签: python


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      相关资源
      最近更新 更多