I am creating a function in Python with the aim of receiving documents in PDF format through the “Make” software and I want to send these documents through the function to a dataset.
While doing the function, the problem faced is as follows:
Internal Error: ValueError: I/O operation on closed file.
from pathlib import Path # noqa: None
import json # Import required to work with JSON
My code looks like this:
from pathlib import Path # noqa: None
import json # Import required to work with JSON
import base64 # Import required to decode Base64
# Absolute path to the JSON file
file_path = Path(__file__).parent / "hash_id.json"
try:
# Opening and reading the JSON file
print(f"Trying to open the file: {file_path}")
with file_path.open("r") as file:
data = json.load(file) # Reading data from JSON
print("Data loaded from JSON:", data)
# Decoding base64
pdf_base64 = data.get("pdf_base64")
if not pdf_base64:
raise ValueError("The key 'pdf_base64' was not found in the JSON file.")
print("Base64 found, decoding...")
pdf_data = base64.b64decode(pdf_base64) # Decodes base64 data to bytes
# Saving the PDF
output_file_path = Path(__file__).parent / "output.pdf"
print(f"Saving the PDF to: {output_file_path}")
with output_file_path.open("wb") as pdf_file:
pdf_file.write(pdf_data)
print(f"PDF successfully saved as '{output_file_path}'")
except FileNotFoundError as e:
print(f"Error: Archive '{file_path}' not found. Make sure it exists in the correct directory.")
except json.JSONDecodeError as e:
print("Error: The JSON archive is poorly formatted or corrupted.")
except ValueError as e:
print(f"Erro: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
Note: In the directory where I am creating the function, I have a file in json format for testing.
If you need any more information, let me know.