NumesSanguis
NumesSanguis

Reputation: 6322

Python Kivy write/read file to SD card

By using Python and Kivy I want to write a file to the (virtual) SD card of the user's phone and also read this file again in a different function. Since Android, IOS and Windows Phone probably have different paths to the SD card, it seems like using 'plyer' is a good idea. How do I write/read a file to/of the SD card?

Upvotes: 5

Views: 6012

Answers (2)

NumesSanguis
NumesSanguis

Reputation: 6322

Path to SD card

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 also works on Android, but it relies on a /sdcard symlink which is becoming outdated. I don't know for IOS or Windows Phone though.

Copy to SD card

import shutil

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

Upvotes: 5

mcastle
mcastle

Reputation: 3002

Use Kivy's user_data_dir to return the path to the directory of the user's file system.

Then use Kivy's storage to store data to a file in the directory.

Upvotes: 1

Related Questions