Search code examples
pythonandroidpython-3.xsave

Python: Permission denied problem on Android


I just wanted to save .mp3 file from a website in /storage/emulated/0/Download folder on Android, but I always get Errno 13 Permission denied.

here's example code:

import requests

# full path to mp3 file in website example
target_link = 'https://www.yt-download.org/download/IFtwhMK64H8/mp3/128/1630338605/f2803874069bf196561631cea2b1b11c2b1d2f9555e2baf751eb28b46d484bb5/0.mp3'

r = requests.get(target_link)

# downloading it into download folder on Android
with open('/storage/emulated/0/Download/file.mp3', 'wb') as f:
    f.write(r.content)

Update: Forgot to say that I used Kivy as GUI framework.


Solution

  • You surely need the WRITE_EXTERNAL_STORAGE permission. On latest Android versions, that permission must be requested explicitly. You then have to use something like this:

    from android.permissions import Permission, request_permissions, check_permission
    
    def check_permissions(perms):
        for perm in perms:
            if check_permission(perm) != True:
                return False
        return True
    
    perms = [Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE]
        
    if  check_permissions(perms)!= True:
        request_permissions(perms)
    

    This will ensure that you have all the required permissions and that the user explicitly granted them. Note that you must check them everytime, because the user can revoke them outside the app.

    The rest of your code looks ok, even if I'd better use primary_external_storage_path(), instead of providing an absolute path.