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

发布于 2024-10-05 00:15:29 字数 104 浏览 2 评论 0原文

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

数理化全能战士 2024-10-12 00:15:29

glob 就是您所需要的。

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

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

glob is what you need.

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

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

硪扪都還晓 2024-10-12 00:15:29

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

如果您愿意,您也可以只过滤 glob() 返回的结果,这样做的好处是可以执行一些操作与 unicode 等相关的额外内容。如果重要的话,请检查 glob.py 中的源代码。

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

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:

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.

[n for n in glob(pattern) if os.path.isfile(n)]
留蓝 2024-10-12 00:15:29
import os
[x for x in os.listdir("your_directory") if len(x) >= 4 and  x[-4:] == ".rar"]
import os
[x for x in os.listdir("your_directory") if len(x) >= 4 and  x[-4:] == ".rar"]
美人迟暮 2024-10-12 00:15:29

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

如果您想使用通配符,可以使用 popen 和 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

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

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

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

If you want to use wildcards, you could use popen with shell = True or os.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.

>>> import glob
>>> glob.glob('*.old')
['projecthelper.old']
>>> 
在巴黎塔顶看东京樱花 2024-10-12 00:15:29

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

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

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
幸福还没到 2024-10-12 00:15:29

显示完整路径并根据扩展名进行过滤,

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

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))]
岁月打碎记忆 2024-10-12 00:15:29

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

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

任谁 2024-10-12 00:15:29

这是使用子进程完成工作的另一种方法。

import subprocess

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文