Python os模块无法获取正确文件路径问题求助
问题根源分析
你踩的坑很典型——os.path.abspath()并不是魔法般能找到任意文件名的实际路径,它只会以当前程序运行的工作目录为基准,把你传入的相对路径(这里就是单纯的文件名)转换成绝对路径。你遍历C:/找到MP3文件时,只保存了文件名,没记录它所在的真实目录,后续调用abspath自然会把当前虚拟环境目录当成文件所在位置,肯定找不到文件。
解决方案
核心思路是:遍历文件时直接保存完整的绝对路径,而不是只存文件名,这样播放时直接用这个路径就行。具体修改如下:
1. 遍历阶段保存完整路径
在on_start方法里,用os.path.join(root, file)拼接出文件的完整绝对路径,然后把这个路径和文件名都关联到列表项上:
def on_start(self): for root, dirs, files in os.walk('C:/'): for file in files: if file.endswith('.mp3'): # 拼接出文件的完整绝对路径 full_path = os.path.join(root, file) # 创建列表项,把完整路径存在custom_data属性里,文本显示文件名 list_item = OneLineListItem(text=file, on_release=self.play_song) list_item.custom_data = full_path self.root.ids.scroll.add_widget(list_item)
2. 播放阶段直接使用保存的路径
修改play_song方法,直接读取列表项的custom_data属性,不用再调用os.path.abspath:
def play_song(self, onelinelistitem): the_song_path = onelinelistitem.custom_data sound = SoundLoader.load(the_song_path) if sound: sound.play() print("播放路径:", the_song_path)
修改后的完整代码
from kivy.lang import Builder from kivymd.uix.list import OneLineListItem from kivymd.app import MDApp from kivy.core.audio import SoundLoader import os helper_string = """ Screen: BoxLayout: orientation: "vertical" ScrollView: MDList: id: scroll """ class MainApp(MDApp): def build(self): screen = Builder.load_string(helper_string) return screen def on_start(self): for root, dirs, files in os.walk('C:/'): for file in files: if file.endswith('.mp3'): full_path = os.path.join(root, file) list_item = OneLineListItem(text=file, on_release=self.play_song) list_item.custom_data = full_path self.root.ids.scroll.add_widget(list_item) def play_song(self, onelinelistitem): the_song_path = onelinelistitem.custom_data sound = SoundLoader.load(the_song_path) if sound: sound.play() print("播放路径:", the_song_path) MainApp().run()
补充说明
os.walk()返回的root是当前遍历到的目录,file是该目录下的文件名,两者用os.path.join拼接就能得到文件的真实绝对路径,这是遍历文件时获取完整路径的标准做法。- 把完整路径存在
custom_data里是KivyMD列表项的常用技巧,既可以在界面显示友好的文件名,又能在交互时拿到背后的实际数据。
内容的提问来源于stack exchange,提问作者Sanyam Pandey
相关产品推荐
相关产品推荐

