You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android平台Kivy+Python写入/storage/emulated/0遇Errno 1权限错误

Android Kivy应用写入外部存储权限问题

我花费数周时间尝试在Android手机上实现文件写入功能,开发环境为Windows PC搭配Anaconda与Pycharm,使用Kivy和Buildozer构建Android应用。测试应用仅需将test.txt写入手机SD卡根目录/storage/emulated/0,但出现错误:[Errno 1] Operation is not permitted: '/storage/emulated/0/test.txt'。我已在代码中申请权限,但应用启动或安装时未弹出权限请求提示。

代码实现

import kivy
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.utils import platform
import os

class MyGridLayout(GridLayout):
    def __init__(self, **kwargs):
        super(MyGridLayout, self).__init__(**kwargs)

        self.cols = 1

        self.dir_button = Button(text="Show Directory")
        self.dir_button.bind(on_press=self.press_dir)
        self.add_widget(self.dir_button)

        self.write_button = Button(text="Write File")
        self.write_button.bind(on_press=self.press_write)
        self.add_widget(self.write_button)

        self.text_field = TextInput(multiline=True)
        self.add_widget(self.text_field)

    def press_dir(self, instance):
        if platform == 'android':
            from android.storage import primary_external_storage_path
            self.file_dir = primary_external_storage_path()
        else:
            self.file_dir = App.get_running_app().user_data_dir

        if not os.path.exists(self.file_dir):
            os.mkdir(self.file_dir)

        self.text_field.text = self.file_dir

    def press_write(self, instance):
        self.file_name = "test.txt"
        self.full_name = os.path.join(self.file_dir, self.file_name)
        try:
            with open(self.full_name, "w") as outfile:
                outfile.write("Hello World")
        except Exception as e:
            self.text_field.text = str(e)

class TestWriteApp(App):
    def build(self):
        return MyGridLayout()

if platform == 'android':
    from android.permissions import request_permissions, Permission
    request_permissions([Permission.WRITE_EXTERNAL_STORAGE,
                         Permission.READ_EXTERNAL_STORAGE])

testwriteapp = TestWriteApp()
testwriteapp.run()

测试情况

  • 点击「Show Directory」按钮:文本框显示路径/storage/emulated/0
  • 点击「Write File」按钮:文本框显示权限错误信息[Errno 1] Operation is not permitted: '/storage/emulated/0/test.txt'

已尝试的解决方法

  • 在buildozer.spec文件中添加权限声明
  • 将文件写入位置改为内部存储的user_data_dir(此方法可行,但无法让用户通过系统Files应用访问生成的文件)

恳请协助解决该问题。

内容的提问来源于stack exchange,提问作者Steve Olekszyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 11:42:34