Python 在 os.path.isfile() 中使用通配符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4296138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:07:43  来源:igfitidea点击:

Use wildcard with os.path.isfile()

pythonpathwildcard

提问by Alex

I'd like to check if there are any .rar files in a directory. it doesn't need to be recursive.

我想检查目录中是否有任何 .rar 文件。它不需要是递归的。

Using wildcard with os.path.isfile() was my best guess, but it doesn't work. What can I do then?

将通配符与 os.path.isfile() 一起使用是我最好的猜测,但它不起作用。那我能做什么?

Thanks.

谢谢。

回答by pyfunc

Wildcards are expanded by shelland hence you can not use it with os.path.isfile()

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

If you want to use wildcards, you could use popen with shell = Trueor os.system()

如果要使用通配符,可以使用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

You could get the same effect with glob module too.

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

>>> import glob
>>> glob.glob('*.old')
['projecthelper.old']
>>> 

回答by user225312

globis what you need.

glob正是你所需要的。

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

os.path.isfile()returns Trueif a path is an existing regular file. So that is used for checking whether a file already exists and doesn't support wildcards. globdoes.

os.path.isfile()True如果路径是现有的常规文件,则返回。所以它用于检查文件是否已经存在并且不支持通配符。glob做。

回答by Mariy

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

回答by Peter Hansen

Without using os.path.isfile()you won't know whether the results returned by glob()are files or subdirectories, so try something like this instead:

如果不使用,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')

You could also just filter the results returned by glob()if you like, and that has the advantage of doing a few extra things relating to unicode and the like. Check the source in glob.py if it matters.

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

[n for n in glob(pattern) if os.path.isfile(n)]

回答by gnetscher

iglob is better than glob here since you do not actually want the full list of rar files, but just want to check that one rar exists

iglob 在这里比 glob 更好,因为您实际上并不想要 rar 文件的完整列表,而只是想检查一个 rar 是否存在

回答by Tchotchke

If you just care about whether at least one file exists and you don't want a list of the files:

如果您只关心是否至少存在一个文件并且您不想要文件列表:

import glob
import os

def check_for_files(filepath):
    for filepath_object in glob.glob(filepath):
        if os.path.isfile(filepath_object):
            return True

    return False

回答by Som

to display full path and filter based on extension,

根据扩展名显示完整路径和过滤器,

import os
onlyfiles = [f for f in os.listdir(file) if len(f) >= 5 and  f[-5:] == ".json" and isfile(join(file, f))]

回答by SUUSHEN_SENJU

Just another method to get the job done using subprocess.

使用子流程完成工作的另一种方法。

import subprocess

try:
        q = subprocess.check_output('ls')
        if ".rar" in q:
             print "Rar exists"
except subprocess.CalledProcessError as e:
        print e.output

Reference : https://docs.python.org/2/library/subprocess.html#subprocess.check_output

参考:https: //docs.python.org/2/library/subprocess.html#subprocess.check_output