Android下使用Flet扫描文件夹仅识别目录,无法获取文件求助
问题描述
通过Flet文件选择器获取文件夹路径后,在Windows系统下可正常获取该文件夹下的所有目录和文件,但在Android系统中仅能检测到目录,无法获取文件。已尝试os.scandir()、os.listdir()及pathlib模块的相关方法,均未解决问题。
代码示例
import flet as ft import os import pathlib def get_files_in_folder(page): # get all folders in folder path page.files={} for k in page.folder_path.keys(): path = pathlib.Path(k) # Get all files and directories all_entries = [child.name for child in path.iterdir()] page.files[k] = all_entries page.update() def main(page: ft.Page): page.folder_path={} def pick_files_result(e: ft.FilePickerResultEvent, page = page): if e.path: page.folder_path[e.path] = e.path selected_path.value = f"path: {e.path}" get_files_in_folder(page) files_in_path.value = f"path: {page.files[e.path]}" page.update() pick_files_dialog = ft.FilePicker(on_result=pick_files_result) # Register the file picker with the page page.overlay.append(pick_files_dialog) floating_action_button = ft.FloatingActionButton( content=ft.Row( [ft.Icon(ft.icons.ADD)], alignment="center", spacing=5 ), shape=ft.CircleBorder(), width=100, mini=True, on_click = lambda _: pick_files_dialog.get_directory_path() ) selected_path = ft.Text(value="No directory selected") files_in_path=ft.Text(value="No files") page.add(floating_action_button) page.add(selected_path) page.add(files_in_path) # Run the Flet app ft.app(target=main)
解决方案
1. 申请Android存储权限
Android 10及以上采用分区存储机制,直接通过文件系统路径访问文件需要对应的权限。修改应用启动代码,添加必要权限:
ft.app( target=main, permissions=[ ft.Permission.READ_EXTERNAL_STORAGE, ft.Permission.WRITE_EXTERNAL_STORAGE ] )
2. 使用Flet原生API获取文件列表
避免直接通过pathlib或os模块访问文件系统,改用Flet的FilePicker.get_files()方法,该方法会自动适配Android的存储规则:
def get_files_in_folder(page, folder_path): # 初始化文件选择器 file_picker = ft.FilePicker() # 获取目标目录下的所有文件和文件夹 all_items = file_picker.get_files( directory=folder_path, allow_multiple=True, file_type=ft.FilePickerFileType.ANY ) # 提取所有条目名称 page.files[folder_path] = [item.name for item in all_items] page.update() def main(page: ft.Page): page.folder_path={} def pick_files_result(e: ft.FilePickerResultEvent, page = page): if e.path: page.folder_path[e.path] = e.path selected_path.value = f"path: {e.path}" # 传入选中的文件夹路径 get_files_in_folder(page, e.path) files_in_path.value = f"entries: {page.files[e.path]}" page.update() # 其余代码保持不变
3. 处理特殊目录访问(Android 11+)
如果需要访问自定义文件夹或非媒体目录,可能需要申请MANAGE_EXTERNAL_STORAGE权限(该权限为特殊权限,需用户手动在设置中开启):
ft.app( target=main, permissions=[ ft.Permission.READ_EXTERNAL_STORAGE, ft.Permission.MANAGE_EXTERNAL_STORAGE ] )
注意:该权限上架Google Play时需符合平台政策,仅在必要时使用。
内容的提问来源于stack exchange,提问作者Sosa
相关产品推荐
相关产品推荐

