Create a new item and attach file in sharepoint api

Hi,
I need to create a new item in the list and also need to attach file in it.
PFB the code which i am using attachment_file.add() method but i am getting a Type error: add() takes 2 positional arguments but 3 were given. Refer to below line of code which is causing error :


target_item.attachment_files.add(file_name, file_data)

Please Look into the below code and help me out in resolving this.

from office365.runtime.auth.client_credential import ClientCredential from office365.sharepoint.client_context import ClientContext import os
 site_url = ‘https://your_sharepoint_site_url’ client_id = ‘your_client_id’ client_secret = ‘your_client_secret’
 credentials = ClientCredential(client_id, client_secret) 
ctx=ClientContext(site_url).with_credentials(credentials)

list_title = ‘Your List Name’ 
target_list = ctx.web.lists.get_by_title(list_title) item_creation_info = { ‘Title’: ‘New Item Title’ } new_item=target_list.add_item(item_creation_info)
ctx.execute_query() 
item_id = new_item.properties[‘Id’]
print(f‘Created item with ID:{item_id}’) 
file_path = ‘path/to/your/file.txt’ 
file_name = os.path.basename(file_path)
with open(file_path, ‘rb’) as file_content:
file_data = file_content.read()
target_item=target_list.get_item_by_id(item_id)
target_item.attachment_files.add(file_name, file_data)
ctx.execute_query()

print(f‘Attached file to item ID: {item_id}’)

Hi,

please use these instructions when entering your script for others to see. It helps with interpreting your script more readily when properly formatted.

Regarding the error that you are receiving, can you copy and paste it at the end of the script. It should include specifically which part is failing.