在 os.path.isfile() 中使用通配符
我想检查目录中是否有 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
glob 就是您所需要的。
如果路径是现有的常规文件,则 os.path.isfile() 返回 True。所以它用于检查文件是否已经存在并且不支持通配符。
glob
确实如此。glob is what you need.
os.path.isfile()
returnsTrue
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.不使用
os.path.isfile()
你不会知道glob()
是文件或子目录,因此请尝试这样的操作:
如果您愿意,您也可以只过滤
glob()
返回的结果,这样做的好处是可以执行一些操作与 unicode 等相关的额外内容。如果重要的话,请检查 glob.py 中的源代码。Without using
os.path.isfile()
you won't know whether the results returned byglob()
are files or subdirectories, so try something like this instead: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.通配符由 shell 扩展,因此您不能将其与 os.path.isfile() 一起使用。
如果您想使用通配符,可以使用
popen 和 shell = True
或os.system()
您也可以使用 glob 模块获得相同的效果。
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
oros.system()
You could get the same effect with glob module too.
如果您只关心是否至少存在一个文件并且不需要文件列表:
If you just care about whether at least one file exists and you don't want a list of the files:
显示完整路径并根据扩展名进行过滤,
to display full path and filter based on extension,
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
这是使用子进程完成工作的另一种方法。
参考: https://docs.python.org/2/library/ subprocess.html#subprocess.check_output
Just another method to get the job done using subprocess.
Reference : https://docs.python.org/2/library/subprocess.html#subprocess.check_output