Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
NumesSanguis Avatar asked May 21 '15 11:05

NumesSanguis


2 Answers

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)
like image 184
NumesSanguis Avatar answered Sep 30 '22 23:09

NumesSanguis


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.

like image 44
mcastle Avatar answered Oct 03 '22 23:10

mcastle