ruslol228
ruslol228

Reputation: 43

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.

Upvotes: 0

Views: 3911

Answers (2)

horus
horus

Reputation: 87

If you are deploying an .apk with BUILDOZER, you have to set the permissions in the .py code, as written above, AND the permissions line must be changed in the .spec file in this way:

android.permissions = android.permission.READ_EXTERNAL_STORAGE,android.permission.WRITE_EXTERNAL_STORAGE

Remember that you can write a file in /storage/emulated/0/Download directory but your code canNOT read a file in that directory if it is not generated by your code.

Upvotes: 0

Gregorio Palamà
Gregorio Palamà

Reputation: 1952

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.

Upvotes: 1

Related Questions