How do I get info of a file selected with fileChooser in Kivy?

squarrel picture squarrel · Nov 1, 2013 · Viewed 13.7k times · Source

How do I grab info of a file I select through the fileChooser? Here are some chunks of code I have:

self.fileChooser = fileChooser = FileChooserListView(size_hint_y=None, path='/home/')
...
btn = Button(text='Ok')
btn.bind(on_release=self.load(fileChooser.path, fileChooser.selection))
...
def load(self, path, selection):
    print path,  selection

What this does is print the path and the selection in the instance when I initially open the fileChooser. When I select a file and click 'Ok', nothing happens.

Answer

Nykakin picture Nykakin · Nov 1, 2013

This example might help you:

import kivy

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

import os

Builder.load_string("""
<MyWidget>:
    id: my_widget
    Button
        text: "open"
        on_release: my_widget.open(filechooser.path, filechooser.selection)
    FileChooserListView:
        id: filechooser
        on_selection: my_widget.selected(filechooser.selection)
""")

class MyWidget(BoxLayout):
    def open(self, path, filename):
        with open(os.path.join(path, filename[0])) as f:
            print f.read()

    def selected(self, filename):
        print "selected: %s" % filename[0]


class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()