Search code examples
pythonandroiddirectorykivy

How can I create a folder on my phone's memory using kivy


I wanna create a folder. Who content some files created by user. But I didn't understand how can to create a folder on my phone's memory.

My folder will be in /storage/emulate/0/Android/data/org.app.test/folder. I'm trying

os.mkdir(str(primary_external_storage_path() + "/Android/data/org.app.test/folder"))

But it doesn't work.

Ps : it could be a problem with android's permission.


Solution

  • Your app will need to ask for storage permissions to be able to access files outside of it's private folder. Below is working example. I changed os.mkdir to os.makedirs to be able to create parent directories of your path.

    main.py

    from kivy import platform
    from kivy.factory import Factory
    from kivy.app import App
    import os
    
    class TestApp(App):
    
        def on_start(self):
            if platform == "android":
                from android.permissions import Permission, check_permission, request_permissions
                perms = [Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE]
                if not all([check_permission(perm) for perm in perms]):
                    Factory.MyPermReqPopup().open()
    
        def popup_close(self):
            from android.permissions import Permission, request_permissions
            request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE])
            exit()
    
        def create_folder_click(self):
            if platform == "android":
                from android.storage import primary_external_storage_path
                os.makedirs(str(primary_external_storage_path()) + "/Android/data/org.app.test/folder", exist_ok=True)
    
    TestApp().run()
    

    test.kv

    BoxLayout:
        orientation: 'vertical'
        size: root.width, root.height
        Button:
            text: 'create folder'
            on_release: app.create_folder_click()
    
    <MyPermReqPopup@Popup>:
        auto_dismiss: False
        on_dismiss: app.popup_close()
        title: 'Please grant storage permission, then launch app again'
        size_hint: (1, 0.3)
        BoxLayout:
            size: root.width, root.height
            Button:
                text: 'OK'
                on_release: root.dismiss()