Windows Error: 32 when trying to rename file in python

人盡茶涼 提交于 2021-01-29 07:00:54

问题


I'm trying to rename some PDF files using pyPdf and my code it seems to work fine until it reaches the rename sentence. The While/if block of code looks for the page number where string "This string" is located and when found stops. Having the page number the "new name" is created.

My issue is that even when the with block it's supposed to close automatically the file, when it's reached the rename sentence I get the error below

Traceback (most recent call last):
File "<stdin>", line 14, in <module>
WindowsError: [Error 32] The process cannot access the file because it is being used by another process

and I don't know how to close the file before rename it, since if I use "file.close()" I get this error

Traceback (most recent call last):
File "<stdin>", line 14, in <module>
AttributeError: 'str' object has no attribute 'close'

My current code is below, thanks for any help on this.

import os
import glob
import sys
from os.path import basename
import pyPdf

path = "C:\\My\\Path\\"
os.chdir(path)  
for file in glob.glob("*.pdf"):
    print file
    i = 0
    with open(file, "rb") as f:
        pdf = pyPdf.PdfFileReader(f)
        while True:
            txt = pdf.pages[i].extractText()
            if "This string" in txt:
                new_name = basename(file) + "_Page_" + str(i)
                break
            i = i + 1   
    print new_name
    #file.close()
    os.rename(file, new_name) # The error occurs here.

* Update *

Without With block I get the same error

for file in glob.glob("*pdf"):
    print file
    i = 0   
    f = open(file, "rb") 
    pdf = pyPdf.PdfFileReader(f)
    while True:
        txt = pdf.pages[i].extractText()
        if "This string" in txt:
            new_name = basename(file) + "_Page_" + str(i)
            break           
        i = i + 1   
    f.close()   
    os.rename(file, new_name)

回答1:


Thanks your advice .But,I remove the variable in my program,and successed. :) In my view ,the file was surely opened in my program ,but I dont know how to c lose it,So I clean All. :(



来源:https://stackoverflow.com/questions/34456243/windows-error-32-when-trying-to-rename-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!