【问题标题】:Checking if a file exists in Python 2.7检查 Python 2.7 中是否存在文件
【发布时间】:2016-06-23 14:49:51
【问题描述】:

我正在使用一个简单的 python 脚本在我的笔记本电脑上搜索和播放歌曲。代码如下:-

    import os
    d_name = raw_input("enter drive name:-")
    choice = raw_input("song or video(s/v):-")
    if(choice == 's'):
        s_name = raw_input("enter song name:- ")
        flag = 1
    elif(choice=='v'):
        s_name = raw_input("enter video name:-")
        flag = 2
    if(flag == 1):
        f_s_name = "start "+d_name+":/"+s_name+".mp3"
    elif(flag == 2):
        f_s_name = "start "+d_name+":/"+s_name+".mp4"
    dir_list = os.listdir("d_name:/")
    i=0
    while(1):
        if(not(os.system(f_s_name))):
            break
        else:
        if(flag == 1):
            f_s_name = "start "+d_name+":/"+dir_list[i]+"/"+s_name+".mp3"
         elif(flag == 2):
            f_s_name = "start "+d_name+":/"+dir_list[i]+"/"+s_name+".mp4"
     i = i+1

上述程序运行良好,但是当对函数 os.system() 的调用之一失败,直到所需条件匹配时,它会弹出一个对话框,声称歌曲在找到之前不存在。如何防止弹出该对话框?

【问题讨论】:

  • 请去掉那些不必要的括号。

标签: python dialog


【解决方案1】:

您将使用os.path.exists 来测试您即将转到start 的文件是否确实存在;如果没有找到,不要尝试start那个文件:

import os

....

filename = '{}:/{}/{}.mp3'.format(d_name, dir_list[i], s_name)
if os.path.exists(filename):
    system('start ' + filename)
else:
    print "File {} was not found".format(filename)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多