Reputation: 31
The code that I'm writing has to rename and change the directory of some PDFs in a certain folder; both the new name and the new directory of a single PDF depend on the content of the PDF itself. The PDFs differ pretty much each other, so it is not trivial to extract the data that I need.
Said that, I decided to proceed in this way:
However I'm not manage to close the opened PDF, so I cannot rename it if it is opened. I wrote this code as an example:
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)
Could you suggest me how to solve this problem? Do you think there is a smarter way to do it?
Regards
Upvotes: 2
Views: 2144
Reputation: 121809
Using os.startfile()
is a rather clever approach, and I'm surprised that it seems to allow you to read (at least SOME) of what you want to read from your .pdf's. Cool!
But you cannot "close" the application (presumably Acrobat Reader, on Windows):
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.
SUGGESTION:
Try using a .pdf library to "open" and "read" from your .pdf's instead. For example, PDFMiner
PS:
os.startfile()
is causing "file in use", hence preventing os.rename()
. Perhaps you can just move/rename the file FIRST?
Upvotes: 2