使用Jupyter中的浏览按钮上传文件并使用/保存它们 [英] Uploading files using Browse Button in Jupyter and Using/Saving them

查看:675
本文介绍了使用Jupyter中的浏览按钮上传文件并使用/保存它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了此片段,用于上传文件在Jupyter但是我不知道如何保存这个文件在执行代码的机器上,或者如何显示上传文件的前5行。基本上,我正在寻找适当的命令来访问文件上传后:

 从IPython导入io 
。显示导入显示
导入fileupload
$ b $ def _upload():

_upload_widget = fileupload.FileUploadWidget()
$ b $ def _cb(change) :
decode = io.StringIO(change ['owner']。data.decode('utf-8'))
filename = change ['owner']。filename
print('上传的格式(
filename,len(decode.read())/ 2 ** 10))

_upload_widget.observe _cb,names ='data')
display(_upload_widget)

_upload()


<当上传完成时调用 c> 。如上面注释中所述,您可以在那里写入文件,或将其存储在变量中。例如:

  from IPython.display import display 
import fileupload

uploader = fileupload .fileUploadWidget()
$ b def _handle_upload(change):
w = change ['owner']
打开(w.filename,'wb')为f:$ b $格式(
w.filename,len(w.data)/ 2 *)b f.write(w.data)
print('Uploaded`{} * 10))

uploader.observe(_handle_upload,names ='data')

display(uploader)

上传完成后,您可以访问文件名:

  uploader.filename 


I came across this snippet for uploading files in Jupyter however I don't know how to save this file on the machine that executes the code or how to show the first 5 lines of the uploaded file. Basically I am looking for proper commands for accessing the file after it has been uploaded:

import io
from IPython.display import display
import fileupload

def _upload():

    _upload_widget = fileupload.FileUploadWidget()

    def _cb(change):
        decoded = io.StringIO(change['owner'].data.decode('utf-8'))
        filename = change['owner'].filename
        print('Uploaded `{}` ({:.2f} kB)'.format(
            filename, len(decoded.read()) / 2 **10))

    _upload_widget.observe(_cb, names='data')
    display(_upload_widget)

_upload()

解决方案

_cb is called when the upload finishes. As described in the comment above, you can write to a file there, or store it in a variable. For example:

from IPython.display import display
import fileupload

uploader = fileupload.FileUploadWidget()

def _handle_upload(change):
    w = change['owner']
    with open(w.filename, 'wb') as f:
        f.write(w.data)
    print('Uploaded `{}` ({:.2f} kB)'.format(
        w.filename, len(w.data) / 2**10))

uploader.observe(_handle_upload, names='data')

display(uploader)

After the upload has finished, you can access the filename as:

uploader.filename

这篇关于使用Jupyter中的浏览按钮上传文件并使用/保存它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆