Windows 错误:尝试在 python 中重命名文件时出现 32 [英] Windows Error: 32 when trying to rename file in python

查看:56
本文介绍了Windows 错误:尝试在 python 中重命名文件时出现 32的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 pyPdf 重命名一些 PDF 文件,我的代码在到达重命名语句之前似乎工作正常.当/如果代码块查找字符串This string"所在的页码,并在找到时停止.将页码设为新名称"已创建.

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.

我的问题是,即使 with 块它应该自动关闭文件,当它到达重命名句子时,我得到下面的错误

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

我不知道如何在重命名之前关闭文件,因为如果我使用file.close()"我会收到这个错误

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.

* 更新 *

没有使用块我得到同样的错误

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)

推荐答案

感谢您的建议.但是,我删除了程序中的变量,并成功了.:)在我看来,该文件肯定是在我的程序中打开的,但我不知道如何丢失它,所以我清除了所有.:(

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. :(

这篇关于Windows 错误:尝试在 python 中重命名文件时出现 32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆