使用带有os.path.isfile()的通配符

Ale*_*lex 33 python wildcard path

我想检查一个目录中是否有.rar文件.它不需要递归.

使用带有os.path.isfile()的通配符是我最好的猜测,但它不起作用.那我该怎么办?

谢谢.

use*_*312 68

glob是你需要的.

>>> import glob
>>> glob.glob('*.rar')   # all rar files within the directory, in this case the current working one
Run Code Online (Sandbox Code Playgroud)

os.path.isfile()True如果路径是现有常规文件,则返回.因此,它用于检查文件是否已存在且不支持通配符.glob确实.

  • 不幸的是,如果不使用 os.path.isfile() 来检查结果,您仍然不知道您找到的是目录还是文件。 (2认同)

Mar*_*riy 10

import os
[x for x in os.listdir("your_directory") if len(x) >= 4 and  x[-4:] == ".rar"]
Run Code Online (Sandbox Code Playgroud)


Pet*_*sen 7

在不使用的情况下,os.path.isfile()您将无法知道返回的结果glob()是文件还是子目录,因此请尝试使用以下内容:

import fnmatch
import os

def find_files(base, pattern):
    '''Return list of files matching pattern in base folder.'''
    return [n for n in fnmatch.filter(os.listdir(base), pattern) if
        os.path.isfile(os.path.join(base, n))]

rar_files = find_files('somedir', '*.rar')
Run Code Online (Sandbox Code Playgroud)

glob()如果你愿意,你也可以只过滤返回的结果,这样做的好处是可以做一些与unicode等相关的额外事情.如果重要,请检查glob.py中的源代码.

[n for n in glob(pattern) if os.path.isfile(n)]
Run Code Online (Sandbox Code Playgroud)


pyf*_*unc 6

通配符由 shell 扩展,因此您不能将它与 os.path.isfile() 一起使用

如果要使用通配符,可以使用popen with shell = Trueos.system()

>>> import os
>>> os.system('ls')
aliases.sh          
default_bashprofile     networkhelpers          projecthelper.old           pythonhelpers           virtualenvwrapper_bashrc
0
>>> os.system('ls *.old')
projecthelper.old
0
Run Code Online (Sandbox Code Playgroud)

您也可以使用 glob 模块获得相同的效果。

>>> import glob
>>> glob.glob('*.old')
['projecthelper.old']
>>> 
Run Code Online (Sandbox Code Playgroud)