2

I just now learning ipywidgets and working with them in Jupyter notebook Python 3. Basically, I'm trying to allow the user to upload multiple files using FileUpload(), then trying to access the content of those files so i can save each of them into the system. I got it working for just one file, but now I'm trying to make it an iterative thing so it can save all of them.

Here is my code to make the FileUpload

from ipywidgets import FileUpload

upload = FileUpload(multiple=True)

upload

then i click the upload widget and upload two .txt files

I printed out what the upload.value looks like:

{'test.txt': {'content': b'hi',
              'metadata': {'lastModified': 152266374855,
                           'name': 'test.txt',
                           'size': 17,
                           'type': 'text/plain'}},
'test2.txt': {'content': b'bye',
              'metadata': {'lastModified': 152266374855,
                           'name': 'test2.txt',
                           'size': 18,
                           'type': 'text/plain'}}}

the first code i wrote to save just one uploaded file worked and saved right into the Jupyter file system

with open("test.txt", "wb") as fp:
     fp.write(upload.data[0])

then i attempted to iterate to do the same for two files (i've tried lots of things, forgive me as I'm not great with dictionaries)

for files in upload.value:
     with open(file, "wb") as fp:
          fp.write(file['content'])

then i realized that that would only access the first key in the dictionary, which was the file name.

i also tried variations of:

for elem in upload.value:
     with open (elem['metadata']['name'], 'wb') as file:
          file.write(elem['content'])

I attempted to do for k,v and add .items() after upload, but I got errors there too. I guess I just can't figure out how to access the values of each file in a for loop...Please let me know if you have any advice, thanks!

hapigolucki
  • 47
  • 1
  • 7

1 Answers1

3

upload.value returns a dictionary, so you need to iterate over the key value pairs by using .items(). Both these below have the same effect, 2 is a bit more condensed.

1) Unpack in the loop

for elem in upload.value.items():
     name, file_info = elem
     with open (name, 'wb') as file:
          file.write(file_info['content'])

2) Or, unpack directly

for name, file_info in upload.value.items():
     with open (name, 'wb') as file:
          file.write(file_info['content'])
ac24
  • 5,325
  • 1
  • 16
  • 31
  • THANK YOU! Worked seamlessly....When I tried to add k, v and .items(), I took out the .value before .items(), so I guess that's why it wasn't working. Thanks so much – hapigolucki Apr 01 '20 at 13:21