I'M TRYING TO UPLOAD PDF FILES TO AN AIRTABLE BASE USING PYTHON, BUT I'M FACING ISSUES WITH THE PROCESS. I'VE TRIED MULTIPLE PYTHON LIBRARIES, BUT NONE OF THEM SEEM TO WORK CORRECTLY FOR MY USE CASE.
Here's the code I've been using (replace with your latest code snippet):
import os
import glob
from airtable import Airtable
# Configure Airtable connection
airtable = Airtable('base_id', 'Table 8', api_key='api_key')
# Path to the folder containing PDFs
pdf_folder = r"C:\Users\camip\Desktop\_adjuntos_prueba"
# Get a list of PDF files in the folder
pdf_files = glob.glob(os.path.join(pdf_folder, "*.pdf"))
for pdf_file in pdf_files:
try:
# Get the name of the PDF file
pdf_name = os.path.basename(pdf_file)
# Extract the number from the file name by removing the extension and converting to int
pdf_number = int(os.path.splitext(pdf_name)[0])
# Get all records from Airtable
records = airtable.get_all(view='Grid view')
# Find records where the name contains the number from the PDF file name
matching_records = [record for record in records if str(pdf_number) in record['fields'].get('Name', '')]
if matching_records:
# If a matching record is found, upload the PDF
record = matching_records[0]['fields']
# Check if there is already an attachment
attachments = record.get('Archivos adjuntos', [])
if attachments:
print(f"PDF {pdf_name} already has an attachment. Not uploaded.")
else:
# Upload the PDF file
airtable.update(matching_records[0]['id'], {'Archivos adjuntos': [{'url': f'attachment://{pdf_name}'}]})
print(f"PDF {pdf_name} uploaded to record {record['Name']}")
else:
print(f"No matching record found for {pdf_name}")
except Exception as e:
print(f"Error processing file {pdf_name}: {str(e)}")
When I run this code, it appears to iterate through each PDF file in the specified folder and attempt to upload it to the corresponding record in Airtable based on a number in the file name. However, no PDF files are actually being uploaded to Airtable.
Can someone please guide me on what I might be doing wrong or suggest a better approach to achieve this task? I'd appreciate any help or insights into resolving this issue.
Please let me know if you need any additional information or clarification regarding my problem.