python通过os.system传递变量

时间:2017-12-29 14:41:07

标签: python

这会在我的目录中获取最新的mp3文件

new_file = [(os.path.getmtime(ft) , os.path.basename(ft))
            for ft in os.listdir(path) if ft.lower().endswith('.mp3')]

new_file.sort()

将最新文件分配给我要播放的文件

playFile = new_file[0][1]

获取文件的目录。

PlayfileDir = os.getcwd() + '\\' + str(playFile)

播放文件。这是我得到错误'PlayfileDir'无法找到的地方。

os.system('start "PlayfileDir"')

2 个答案:

答案 0 :(得分:1)

由于PlayfileDir是一个string的变量,您只需将其连接到'start'(如@cdarke指出的那样,您还需要添加引号!)。正如您现在所做的那样,您正在尝试启动实际的字符串'PlayfileDir',而不是变量中的字符串。

所以,你应该这样做:

os.system('start "' + PlayfileDir + '"')

答案 1 :(得分:0)

这是开始使用pathlib的绝佳机会!

from pathlib import Path

p = input("Gimme a path: ")

newest_mp3 = sorted(Path(p).glob('*.mp3'), reverse=True, key=lambda p: p.stat().st_mtime)[0]

os.system('start "{}"'.format(newest_mp3))
相关问题