首页 > 解决方案 > 使用 PyPDF2 重命名文件时如何解决 PermissionError: [WinError 32]?请继续关注,.close() 不是答案

问题描述

我从 python 开始,我有一个小问题。我正在尝试编写一个应用程序来重命名文件夹中的文件。

运行程序时出现以下错误: PermissionError: [WinError 32] File is being used by another process 我相信这种情况正在发生,因为 IDE 仍在访问该文件,但我不知道如何阻止它这样做。我读过的每篇文章都使用 .close() 推荐此错误,但这并不能解决问题。

from PyPDF2 import PdfFileReader
import os

local_doc = input(r"Onde está o arquivo?") 
os.chdir(local_doc)                        

def n_folhas(localdoc,x):
    integral = os.listdir(local_doc)[x] 
    reader = PdfFileReader(integral)
    folhas = reader.getNumPages()
    return(folhas)

folhas = n_folhas(local_doc,0)

print (folhas)

os.listdir(local_doc)[0]
os.rename(local_doc, "CÓPIA INTEGRAL. FLS. 1 A "+str(folhas)+'.pdf')

很抱歉语言和代码一团糟,这是我的第一个实际代码。

谢谢你,祝你有美好的一天!

标签: pythonpypdf2

解决方案


这是完整的答案。

根据我的评论,代码存在许多问题,但主要问题是您调用os.rename不正确并尝试重命名当前工作文件夹,Windows 正确指出该文件夹正在使用中。

未来学习注意事项:请看Pathlibf stringsPathlib是处理文件和文件夹对象的更现代的 Python 方法。f strings是在动态字符串中包含变量和表达式的最新方法。

from PyPDF2 import PdfFileReader
import os

# Get the location of the PDF
# Also current working directory in case we need to switch back
local_doc = input(r"Onde está o arquivo?")
start_dir = os.getcwd()
os.chdir(local_doc)

# Get all the PDF files inside the given location
list_of_pdf = [ pdf_file for pdf_file in os.listdir() if pdf_file.endswith(".pdf") ]

# We have the list of files, only need to give the function
# the specific file
def n_folhas(integral):
    reader = PdfFileReader(integral)
    folhas = reader.getNumPages()
    os.rename(integral, f"CÓPIA INTEGRAL. FLS. 1 A {str(folhas)}.pdf")
    return

# Call the function and give it the 
# first file from the list of PDF files
n_folhas(list_of_pdf[0])

推荐阅读