FileNotFoundError:[WinError 2]系统找不到指定的文件

时间:2015-03-08 12:16:43

标签: python python-3.x

如果我能够对我遇到的问题遇到一些问题,我将不胜感激。代码的目的是识别新创建的目录,以便可以将它们手动添加到磁带库以进行备份。我得到的问题,并不总是可复制的,是当删除目录时,代码会丢失。这是我收到的错误:

G:\Development\Python\Imaging In progress>Imaging_In_Progress.py
2015-03-02 08-41
{} Missing!
Traceback (most recent call last):
  File "G:\Development\Python\Imaging In progress\Imaging_In_Progress.py", line 21, in <module>
    seconds = os.path.getctime(dir)
  File "C:\Python34\lib\genericpath.py", line 65, in getctime
    return os.stat(filename).st_ctime
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'S:\\12345'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "G:\Development\Python\Imaging In progress\Imaging_In_Progress.py", line 27, in <module>
    print("{} Missing!").format(dir)
AttributeError: 'NoneType' object has no attribute 'format'

我理解为什么会出现错误,虽然我不清楚为什么它会出现在某些目录而不是其他目录上。我确实尝试添加一个异常,希望如果发生FileNotFoundError,它将被忽略,脚本将继续。这似乎不是这种情况,可能是由于例外的放置?

请在下面找到我的代码:

import time
import os

#Acquires current time
from datetime import datetime
current_time = str(datetime.now())
current_time = (time.strftime('%Y-%m-%d %H-%M'))
print(current_time)

OUTPUT_FILE = ("{}.txt".format(current_time))

NEW_DIRS =[]

while 1:
#Acquires list of dirs and the creation date attribute associated to them 
    for dir in os.listdir("S:\\"):
        dir = os.path.join("S:\\", dir)
        if os.path.isdir(dir):

            try:
                seconds = os.path.getctime(dir)
                datecreated = (time.strftime('%Y-%m-%d %H:%M', time.localtime(seconds)))


            except (FileNotFoundError, IOError,AttributeError):
                print("{} Missing!").format(dir)


            close_time = "23-59"

            DATE_TIME = str(datetime.now())
            DATE_TIME = (time.strftime('%H-%M'))

            if DATE_TIME == close_time:
                    quit()

            elif dir not in NEW_DIRS and datecreated > current_time:
                with open(OUTPUT_FILE,"a") as c:
                    c.write("{}\n".format(dir))
                    NEW_DIRS.append(dir)
                    print ("{} added to array".format(dir))

1 个答案:

答案 0 :(得分:0)

在您的代码中,

print("{} Missing!").format(dir)
format返回的值调用

print(...)None。这就是你得到这个错误的原因:

AttributeError: 'NoneType' object has no attribute 'format'

修复是调整右括号:

print("{} Missing!".format(dir))

请记住,无论何时看到

During handling of the above exception, another exception occurred:

这意味着您的异常处理代码引发了自己的错误。这可能表示except子句中的代码有问题。