python - 使用 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')
很抱歉语言和代码一团糟,这是我的第一个实际代码。
谢谢你,祝你有美好的一天!
解决方案
这是完整的答案。
根据我的评论,代码存在许多问题,但主要问题是您调用os.rename
不正确并尝试重命名当前工作文件夹,Windows 正确指出该文件夹正在使用中。
未来学习注意事项:请看Pathlib
和f strings
。Pathlib
是处理文件和文件夹对象的更现代的 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])
推荐阅读
- php - Laravel - 雄辩的关系不起作用
- tsql - TSQL 从 1 对 N 关系多次更新同一行
- c++ - 一个同时接受 std::vector 和 QVector 的函数模板?
- html - Karma 在 chrome 中启动和关闭自身
- go - 在 TFS 构建创建中找不到 Go 语言模板
- python - Python:识别按下了哪些键,处理所有按下的键,然后打印结果
- ocaml - OCaml 中的语法:修改后传递数组
- python - Python Pytest 解压夹具
- python-3.x - Tensorflow 和 Keras 中的相同(?)神经网络架构在相同数据上产生不同的准确性
- jquery - Html 不呈现 Jquery 中的附加元素