我的 kivy 应用程序需要一个导出文本文件的导出按钮。我知道保存文件的标准 python 方式,但我无法在 Android 设备上获得我需要的内容。理想情况下,可以在应用程序外部轻松访问文本文件,例如在
"My Files/Documents"
文件夹或类似文件夹中。 (根据我在网上阅读的内容,编写这样的文件不需要任何 Android 权限?这是正确的吗?)
我在网上没有找到可以帮助我实现这一目标的正确信息。下面是我的示例代码,它使用
user_data_dir
中的 App()
属性工作,但文件保存在一个困难的位置。有没有办法修改代码以便将文件保存在 Documents 文件夹中?我发现了这个https://karobben.github.io/2021/03/12/Python/kivy-write2android/,从我可以看到“下载目录的绝对路径是:/storage/emulate/0/Download
”。所以我尝试了这个,错误!我也尝试过“/Internal stoarge/Documents
,还有错误(no such file in both Errors)
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from os.path import join, dirname
from kivy.properties import StringProperty
class Main(BoxLayout):
pass
class TestApp(App):
path = StringProperty("Path")
ToPrint = ["Hello", "World", "This", "Is", "A", "Kivy", "App"]
def Export(self):
self.path = join(dirname(self.user_data_dir), "Sentence.txt")
doc = open(self.path, 'w')
for word in self.ToPrint:
doc.write(f"{word}\n")
doc.close()
def build(self):
return Main()
TestApp().run()
还有KV文件:
<Main>:
padding: "20px"
spacing: "20px"
orientation: "vertical"
Label:
text: app.path
Button:
text: "Click here to save the file"
on_press: app.Export()
我遵循了 python-for-android 上的 storage-path 文档,并且能够将测试文件保存在 Android 上的 Documents 文件夹中。
首先,我们必须请求对外部存储进行写入/读取的权限:
from kivy import platform
if platform == "android":
from android.permissions import request_permissions, Permission
request_permissions([Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE])
其次我们可以看看什么是主要存储位置:
path = primary_external_storage_path()
print(path)
一旦知道路径,您就可以构建相对于该路径的文档路径。我将
adb shell ls
与 cd
结合使用来浏览目录。我将路径构造为 os.path.join(path,'../../sdcard0/Documents/myfile2.txt'
并在文件中写入一些字符串以进行测试。
现在我们可以使用 adb 作为
adb pull storage/sdcard0/Documents/myfile2.txt out/put/path/on/local/machine
从 Android 中提取文件。就是这样。这是一段工作代码:
from kivy.base import runTouchApp
from kivy.uix.boxlayout import BoxLayout
import os
from android.storage import primary_external_storage_path
# get write/read permission
from kivy import platform
if platform == "android":
from android.permissions import request_permissions, Permission
request_permissions([Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE])
path = primary_external_storage_path()
print(path)
with open(os.path.join(path,'../../sdcard0/Documents/myfile2.txt'), 'w') as f:
f.write('good luck Jithesh, you are doing great!')
box = BoxLayout()
runTouchApp()