2016-03-02 204 views
-1

我试图删除多个文件。 我正在使用这个脚本,但由于某种原因它只删除了前4个而不是其他的。如果我将它分解为2个脚本,它会起作用...我的问题是什么?Python - 删除多个文件

def fileDeleter(): 
    try: 
     os.remove('apps.csv') 
     os.remove('columns.txt') 
     os.remove('columns_boot.txt') 
     os.remove('output.txt') 
     os.remove('routes.csv') 
     os.remove('route_apps.txt') 
     os.remove('route_domain.txt') 
     os.remove('route_hosts.txt') 
     os.remove('start.txt') 
     os.remove('space.txt') 
    except OSError: 
     pass 

我的观点是静静地处理它们,如果文件激发然后删除 - 如果不通过。用户不需要看到文件不存在的错误。当我说的错误,我得到的只有一个是

WindowsError: [Error 2] The system cannot find the file specified: *filename*

whice是好的,becuse我没有所有的文件,所有的时间。但是当我这样做时,脚本并不会删除它们。

+1

什么是错误?我认为这将有所帮助,如果'except:'不仅仅是'pass' – Ian

回答

0

一旦发现错误,程序会继续。你需要做的是试图一次删除每个文件,并检查是否有错误。

fileList = ['apps.csv', 'columns.txt', 'columns_boot.txt', 'output.txt', 'routes.csv', 'route_apps.txt', 'route_domain.txt', 'route_hosts.txt', 'start.txt', 'space.txt'] 
for file in fileList: 
    try: 
     os.remove(file) 
    except OSError as e: 
     print("File '{}' could not be removed.".format(file)) 
     # pass # => you really should do more than pass here... 

这样,如果在其中一个早期文件中发生错误,它将不会使程序短路。

+0

这很好。感谢:) 我将使用打印出于调试目的。 – Magnum

0

您的主要问题似乎是您无声处理异常,因此您无法了解其他问题。你可能有更多的问题,但那是最明显的问题。

+0

我的观点是静静地处理它们,如果文件激发然后删除 - 如果不通过。用户不需要看到文件不存在的错误。 当我添加错误,我得到的唯一一个是'代码WindowsError:[错误2]系统找不到指定的文件:' – Magnum

+0

所以现在你知道你的其他问题是什么,其中一个指定的文件不extst。 – Goyo

+0

为什么它“尝试”,并不是所有的文件都应该在那里。 – Magnum