【问题标题】:How can I check for basename (only part of the name) file existence using Python?如何使用 Python 检查基本名称(仅名称的一部分)文件是否存在?
【发布时间】:2015-07-24 08:15:13
【问题描述】:

我认为标题说明了一切。我需要检查名称中包含单词data 的文件是否存在。我尝试了类似 os.path.exists(/d/prog/*data.txt) 的方法,但它不起作用。

【问题讨论】:

    标签: python filenames partial exists


    【解决方案1】:

    你不能只用os.path.exists 来做——它需要完整的路径名。如果不知道确切的文件名,你应该首先在文件系统上找到这个文件(当你这样做时,它证明文件存在)。

    一种选择是列出目录(-ies),然后手动查找文件:

    >>> import os
    >>> file_list = os.listdir('/etc')
    >>> [fn for fn in file_list if 'deny' in fn]
    ['hostapd.deny', 'at.deny', 'cron.deny', 'hosts.deny']
    

    另一个更灵活的选择是使用glob.glob,它允许使用诸如*、?和[...]等通配符:

    >>> import glob
    >>> glob.glob('/etc/*deny*')
    ['/etc/hostapd.deny', '/etc/at.deny', '/etc/cron.deny', '/etc/hosts.deny']
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Windows:

      >>> import glob
      >>> glob.glob('D:\\test\\*data*')
      ['D:\\test\\data.1028.txt', 'D:\\test\\data2.1041.txt']
      

      【讨论】:

        【解决方案3】:

        试试glob吧:

        from glob import glob
        if glob('/d/prog/*data.txt'):
            # blah blah 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-11-23
          • 1970-01-01
          • 1970-01-01
          • 2013-01-19
          • 1970-01-01
          • 1970-01-01
          • 2015-11-03
          相关资源
          最近更新 更多