2016-03-02 60 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