我正在编写的代码必须重命名并更改某个文件夹中某些 PDF 的目录;单个 PDF 的新名称和新目录都取决于 PDF 本身的内容。这些 PDF 彼此之间差异很大,因此提取我需要的数据并非易事。
话虽如此,我决定这样做:
- 打开并显示 PDF;
- 在打开的PDF中手动搜索我需要的参数;
- 将找到的参数作为输入;
- 关闭 PDF;
- 使用他的新名称和新目录重命名 PDF。
但是,我无法关闭打开的 PDF,因此如果打开它,我无法重命名它。我编写了这段代码作为示例:
import os
oldpath = "C:\\Users\Desktop\Training/"
os.chdir = oldpath
for oldname in os.listdir(oldpath):
os.startfile(oldname)
print("Parameter 1")
P1 = input()
print("Parameter 2")
P2 = input()
print("Parameter 3")
P3 = input()
#I want to close the opened file here
newpath = oldpath + "/" + P1 + "/" + P2 + "/"
newname = P3 + ".pdf"
os.rename(oldpath + "/" + oldname, newpath + "/" + newname)
你能建议我如何解决这个问题吗?您认为有更聪明的方法吗?
问候
最佳答案
使用 os.startfile() 是一种相当聪明的方法,我很惊讶它似乎允许您阅读(至少一些)您想要的内容想要阅读您的 .pdf 文件。酷!
但是您无法“关闭”应用程序(可能是 Windows 上的 Acrobat Reader):
https://docs.python.org/3/library/os.html
startfile()
returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application’s exit status.
建议:
尝试使用 .pdf 库来“打开”和“读取”.pdf 文件。例如,PDFMiner
- https://www.blog.pythonlibrary.org/2018/05/03/exporting-data-from-pdfs-with-python/
- https://dzone.com/articles/exporting-data-from-pdfs-with-python
附注:
os.startfile()
导致“文件正在使用”,因此阻止了 os.rename()
。也许您可以先移动/重命名该文件?
关于python - 使用 python 关闭 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55677712/