Python Kivy write/read 文件到SD卡

Python Kivy write/read file to SD card

通过使用 Python 和 Kivy,我想将文件写入用户 phone 的(虚拟)SD 卡,并在不同的函数中再次读取该文件。由于 Android、IOS 和 Windows Phone 可能有不同的 SD 卡路径,因此使用 'plyer' 似乎是个好主意。 我如何write/read一个文件to/ofSD卡?

使用Kivy的user_data_dir来return用户文件系统目录的路径

然后使用Kivy的storage将数据存储到目录中的一个文件中。

SD 卡路径

from jnius import autoclass  # SDcard Android

# Get path to SD card Android
try:
    Environment = autoclass('android.os.Environment')
    sdpath = Environment.getExternalStorageDirectory()

# Not on Android
except:
    sdpath = App.get_running_app().user_data_dir

user_data_dir 也适用于 Android,但它依赖于一个正在变得过时的 /sdcard 符号链接。不过我不知道 IOS 或 Windows Phone。

复制到SD卡

import shutil

sdpathfile = os.path.join(sdpath, 'filename')
shutil.copyfile(os.path.join('folder', 'filename2'), sdpathfile)