2016-10-19 266 views
0

我正在使用python 2並已閱讀關於此錯誤的多個帖子,即(this post)。 但是,我仍然收到錯誤。 我所做的是: 我讀取目錄中的文件,如果任何文件包含特定的字符串,我刪除該目錄。python 2 [錯誤32]進程無法訪問該文件,因爲它正在被另一個進程使用

def select_poo(): 
path = os.walk('/paila_candonga/') 
texto = 'poo' 
extension = '.tex' 
for root, dirs, files in path: 
    for documento in files: 
     if extension in documento: 
      with open(os.path.join(root, documento), 'r') as fin: 
       for lines in fin: 
        if texto in lines: 
         shutil.rmtree(root) 
        else: 
         continue 

然後我得到的錯誤:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process 

我已經使用絕對路徑也試過:

def select_poo(): 
path = os.walk('/paila_candonga/') 
texto = 'poo' 
extension = '.tex' 
for root, dirs, files in path: 
    for documento in files: 
     if extension in documento: 
      with open(os.path.join(root, documento), 'r') as fin: 
       for lines in fin: 
        if texto in lines: 
         route = (os.path.join(root, documento)) 
         files = os.path.basename(route) 
         folder = os.path.dirname(route) 
         absolut= os.path.dirname(os.path.abspath(route)) 
         todo = os.path.join(absolut, files) 
         print todo 

        else: 
         continue 

然後我將獲得:

C:\paila_candonga\la_Arepa.tex 
C:\paila_candonga\sejodio\laOlla.tex 
C:\paila_candonga\sejodio\laPaila.tex 

如果我一次刪除一個文件,使用相同的絕對路徑d os.remove(''),我不會有問題。如果我嘗試使用select_poo()和shutil.rmtree(文件夾)或os.remove(絕對)一次性刪除所有文件,我將會出現錯誤32.

是否有辦法通過每個循環在todo中的路徑,並刪除它們沒有錯誤32?

感謝,

回答

1

它發生在這裏:

with open(os.path.join(root, documento), 'r') as fin: 

所以,你有你的文件打開並鎖定,這就是爲什麼你使用無法刪除此文件夾:

shutil.rmtree(root) 

內此聲明,您必須在with聲明外面做

+0

感謝Alex,但它不會工作。該錯誤仍然存​​在=( –

+0

@Chüngel你確定你沒有這個文件夾或任何其他應用程序中打開此文件夾中的任何文件? – Alex

+0

亞歷克斯,我很新的Python,但如果我刪除使用操作系統的文件.remove(絕對)相同的文件將被刪除而沒有錯誤。所以我相信這個錯誤是由我在同一時間刪除所有文件的過程所引起的。正如你所建議的,我定義了一個變量x = [],然後if在文檔中找到字符串,路徑將被附加到x,然後在with語句之外,我執行os.remove(x [0]),但是我得到了完全相同的錯誤。我的代碼基於你的想法? –

相關問題