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!
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With