0

I am aware you are can upload multiple files to post in an api using this,

ex.

test_files = {
    "test_file_1": open("my_file.txt", "rb"),
    "test_file_2": open("my_file_2.txt", "rb"),
    "test_file_3": open("my_file_3.txt", "rb")
}

but i want to change the files often so the solution i thought of is to drop all the files in a folder and loop through the folder to upload each file.

the part i am stuck on is how can i loop though the folder

path = "/Users/mycode/Documents/API_upload/"

files = {
    'file': open(p,'rb') for p in os.listdir(path)
}

I tried this but doesnt work as the files need to be in the directory for it to work. any other suggestions for this.

thanks.

2
  • "files need to be in the directory for it to work" then where are those files? Commented Jun 11, 2022 at 1:12
  • sorry i should have added the directory. its with in path. i just edited it! Commented Jun 11, 2022 at 1:14

1 Answer 1

1

You need to add base path to the file name

path = "/Users/mycode/Documents/API_upload/"

files = {f'file_{i}': open(f'{path}/{name}','rb') for i, name in enumerate(os.listdir(path))}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! I used files = {f'file': open(f'{path}/{name}','rb') for i, name in enumerate(os.listdir(path))} and it works!! I have been stuck on this for a while but that made my code work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.