I have a python script which aims to rename pdf files based on specific content of the pdf. I am having trouble when the content is not found. The aim is to move that file to a new folder to be manually renamed.
I get windows permission error 32 from within shutil.
I have checked that the file is not open in any apps.
I closed all apps except pycharm.I have no other projects open.
This is the section of code related to the file:
# Scan all files in the origin directory for filename in os.listdir(origin_directory): # Get file path file_path = os.path.join(origin_directory, filename) print('line 34 '+ f"File path: {file_path}") # Open file for reading # with open(file_path, "r", encoding="utf-8", errors="ignore") as file: # with fitz.open(os.path.join(origin_directory, filename), "r") as doc: with fitz.open(os.path.join(origin_directory, filename), ) as doc: print("line 42") found_Inv_no = False # Iterate through each line for line in doc: try: text = line.get_text("utf-8") except UnicodeDecodeError: print(f"Warning: Unable to decode line content using utf-8: {line}") continue # Skip to the next line # Check for any of the search terms for term in invoice_no_search_terms: if term in line.get_text("utf-8"): # Extract numbers after the term (on the same line) match = re.findall(r"\d+", line[line.find(term):], re.IGNORECASE) invoice_numbers.extend(match) found_Inv_no = True print("line 58") fitz.close(doc) break # No search terms found, move file to holding directory if not found_Inv_no: doc.close() # Close the pdf file being read before moving moved_name=("moved " + filename) print (moved_name) new_file_path = os.path.join(holding_Directory, moved_name) print(f"Moving file from {file_path} to {new_file_path}") shutil.move(file_path, new_file_path) print("done") print(filename)
So, i have shutil moving and renaming the file successfully.The print statements confirm that the for loop is not working and it is breaking down with fitz. It seems that the previous filename is being used by fitz but I don't know how to verify this.the new error message is:Traceback (most recent call last):File "C:\Users\AdamYates\PycharmProjects\RenamePdfmaster\ReanemPDFMaster.py", line 41, in with fitz.open(os.path.join(origin_directory, filename), ) as doc:File "C:\Users\name\PycharmProjects\RenamePdf.venv\Lib\site-packages\fitz\fitz.py", line 5893, in exitself.close()File "C:\Users\name\PycharmProjects\RenamePdf.venv\Lib\site-packages\fitz\fitz.py", line 5874, in closeraise ValueError("document closed")ValueError: document closed