8

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

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()
4

4 回答 4

8

_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
于 2016-09-15T08:51:39.257 回答
4

我正在使用 Jupyter notebook 进行 ML,我正在寻找一种解决方案,通过在本地文件系统中浏览来选择包含数据集的本地文件。虽然,这里的问题更多地是指上传而不是选择文件。我在这里放了一个我在这里找到的片段,因为当我为我的特定案例寻找解决方案时,搜索结果让我多次来到这里。

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
于 2018-09-13T16:55:35.160 回答
2

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
于 2020-11-12T12:49:47.110 回答
1

我晚了约 2 年偶然发现了这个线程。对于那些仍然对如何使用文件上传小部件感到困惑的人,我已经建立了 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 输入)创建一个新的 pandas 数据框:

import pandas as pd
from io import StringIO

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

于 2019-02-04T16:29:30.027 回答