使用Jupyter中的“浏览”按钮上载文件并使用/保存它们

时间:2016-09-14 17:01:45

标签: python file-upload ipython jupyter-notebook ipywidgets

我遇到this snippet用于在Jupyter上传文件但是我不知道如何在执行代码的机器上保存此文件或如何显示上传文件的前5行。基本上我正在寻找在上传文件后访问文件的正确命令:

(=<<) f = iter_map wrap f

4 个答案:

答案 0 :(得分:4)

上传完成后会调用

_cb。如上面的注释所述,您可以在那里写入文件,或将其存储在变量中。例如:

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)

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

uploader.filename

答案 1 :(得分:0)

我正在使用Jupyter笔记本进行ML,并且正在寻找一种解决方案,以通过在本地文件系统之间浏览来选择包含数据集的本地文件。虽然,这里的问题更多是关于上传而不是选择文件。我将此处找到的代码段放在here中,是因为当我在寻找针对特定案例的解决方案时,搜索结果将我带到这里了好几次。

import os
import ipywidgets as widgets

class FileBrowser(object):
    def __init__(self):
        self.path = os.getcwd()
        self._update_files()

    def _update_files(self):
        self.files = list()
        self.dirs = list()
        if(os.path.isdir(self.path)):
            for f in os.listdir(self.path):
                ff = os.path.join(self.path, f)
                if os.path.isdir(ff):
                    self.dirs.append(f)
                else:
                    self.files.append(f)

    def widget(self):
        box = widgets.VBox()
        self._update(box)
        return box

    def _update(self, box):

        def on_click(b):
            if b.description == '..':
                self.path = os.path.split(self.path)[0]
            else:
                self.path = os.path.join(self.path, b.description)
            self._update_files()
            self._update(box)

        buttons = []
        if self.files:
            button = widgets.Button(description='..', background_color='#d0d0ff')
            button.on_click(on_click)
            buttons.append(button)
        for f in self.dirs:
            button = widgets.Button(description=f, background_color='#d0d0ff')
            button.on_click(on_click)
            buttons.append(button)
        for f in self.files:
            button = widgets.Button(description=f)
            button.on_click(on_click)
            buttons.append(button)
        box.children = tuple([widgets.HTML("<h2>%s</h2>" % (self.path,))] + buttons)

并使用它:

f = FileBrowser()
f.widget()
#   <interact with widget, select a path>
# in a separate cell:
f.path # returns the selected path

答案 2 :(得分:0)

我迷路了大约2年。对于那些仍然对如何使用fileupload小部件感到困惑的人,我借鉴了minrk发布的出色答案以及下面的一些其他用法示例。

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)

来自小部件文档:

class FileUploadWidget(ipywidgets.DOMWidget):
    '''File Upload Widget.
    This widget provides file upload using `FileReader`.
    '''
    _view_name = traitlets.Unicode('FileUploadView').tag(sync=True)
    _view_module = traitlets.Unicode('fileupload').tag(sync=True)

    label = traitlets.Unicode(help='Label on button.').tag(sync=True)
    filename = traitlets.Unicode(help='Filename of `data`.').tag(sync=True)
    data_base64 = traitlets.Unicode(help='File content, base64 encoded.'
                                    ).tag(sync=True)
    data = traitlets.Bytes(help='File content.')

    def __init__(self, label="Browse", *args, **kwargs):
        super(FileUploadWidget, self).__init__(*args, **kwargs)
        self._dom_classes += ('widget_item', 'btn-group')
        self.label = label

    def _data_base64_changed(self, *args):
        self.data = base64.b64decode(self.data_base64.split(',', 1)[1])

以字节串格式获取数据:

uploader.data

以常规utf-8字符串获取数据:

datastr= str(uploader.data,'utf-8')

从utf-8字符串(例如,从.csv输入)创建新的熊猫数据框:

import pandas as pd
from io import StringIO

datatbl = StringIO(datastr)
newdf = pd.read_table(datatbl,sep=',',index_col=None)

答案 3 :(得分:0)

4年后,这仍然是一个有趣的问题,尽管Fileupload略有变化并属于ipywidgets...。

下面是一些演示,演示了如何在单击按钮后获取文件和重置按钮以获取更多文件...。

from ipywidgets import FileUpload

def on_upload_change(change):
    if not change.new:
        return
    up = change.owner
    for filename,data in up.value.items():
        print(f'writing [{filename}] to ./')
        with open(filename, 'wb') as f:
            f.write(data['content'])
    up.value.clear()
    up._counter = 0

upload_btn = FileUpload()
upload_btn.observe(on_upload_change, names='_counter')
upload_btn

这是一个“调试”版本,显示发生了什么/事情为什么起作用...

from ipywidgets import FileUpload

def on_upload_change(change):
    if change.new==0:
        print ('cleared')
        return
    up = change.owner
    print (type(up.value))
    for filename,data in up.value.items():
        print('==========================================================================================')
        print(filename)
        for k,v in data['metadata'].items():
            print(f'    -{k:13}:[{v}]')
        print(f'    -content len  :[{len(data["content"])}]')
        print('==========================================================================================')
    up.value.clear()
    up._counter = 0

upload_btn = FileUpload()
upload_btn.observe(on_upload_change, names='_counter')
upload_btn