簡體   English   中英

使用 PyPDF2 重命名文件時如何解決 PermissionError: [WinError 32]? 請繼續關注,.close() 不是答案

[英]How do i solve PermissionError: [WinError 32] when renaming files with PyPDF2? Stay tuned, .close() is not the answer

我從 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 正確指出正在使用中。

未來學習注意事項:請看一下Pathlibf 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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM