Kivy应用安卓端无法创建或查找TXT文件问题求助
Hey there, this is a super common pitfall when moving Kivy apps from desktop to Android—let’s break down the key fixes step by step:
1. Handle Android Storage Permissions
Android locks down storage access by default, especially on API 23 (Android 6.0) and above. You need both declared permissions in your build config and dynamic permission requests in code.
Update Buildozer.spec
Add these lines to your buildozer.spec to declare required permissions:
android.permissions = WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE
Request Permissions in Code
Add this snippet early in your app (like in your App class’s on_start method):
from kivy.utils import platform if platform == 'android': from android.permissions import request_permissions, Permission # Trigger permission request on app launch request_permissions([Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE])
2. Use Android-Compliant File Paths
Desktop-style paths (like ./my_file.txt or absolute system paths) won’t work on Android. You need to use the OS’s designated storage directories to ensure write access and make files easy to find.
Get a Valid Save Directory
Use this helper function to target the user-accessible Documents folder:
import os from kivy.utils import platform def get_valid_save_path(): if platform == 'android': from android.storage import primary_external_storage_path # Get the primary external storage's Documents directory docs_dir = os.path.join(primary_external_storage_path(), 'Documents') # Create the directory if it doesn't exist if not os.path.exists(docs_dir): os.makedirs(docs_dir) return docs_dir else: # Fallback for desktop testing return os.getcwd()
Save Your File Correctly
Use the path from the helper function when writing your TXT file:
save_dir = get_valid_save_path() file_path = os.path.join(save_dir, 'my_app_data.txt') with open(file_path, 'w') as f: f.write("This should save correctly on Android!")
3. Debug to Verify the File Path
It’s easy to guess the wrong location—add debug output to confirm where your file is being saved:
from kivy.uix.popup import Popup from kivy.uix.label import Label # After saving, show the path in a popup for quick verification popup = Popup( title="File Saved", content=Label(text=f"Check this location:\n{file_path}"), size_hint=(0.8, 0.4) ) popup.open()
You can also check the app’s logs via adb logcat to catch any hidden file-write errors.
4. Handle Scoped Storage (Android 10+)
If your app targets API 29 or higher, Android’s Scoped Storage restricts direct external storage access. For simple text files, saving to the Documents directory (as shown above) still works, but if you hit roadblocks:
- Temporarily set
android.api = 28inbuildozer.specto target an older API level - Or implement the Storage Access Framework (SAF) for full compliance (more advanced)
内容的提问来源于stack exchange,提问作者Ben Mason

