全局字符和方括号字符 ('[]')
/Users/smcho/Desktop/bracket/[10,20] 目录有“abc.txt”,但是当我运行此 Python 代码时
import glob
import os.path
path1 = "/Users/smcho/Desktop/bracket/\[10,20\]"
pathName = os.path.join(path1, "*.txt")
print glob.glob(pathName)
它返回一个空列表。
- Python 的 glob 不能处理括号字母或其他字母吗?
- 有什么办法可以解决这个问题吗?
/Users/smcho/Desktop/bracket/[10,20] directory has "abc.txt", but when I run this Python code
import glob
import os.path
path1 = "/Users/smcho/Desktop/bracket/\[10,20\]"
pathName = os.path.join(path1, "*.txt")
print glob.glob(pathName)
It returns an empty list.
- Can't Python's glob handle the bracket letters or others?
- Is there any way to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
glob
中的括号用于字符类(例如,[az]
将匹配小写字母)。您可以将每个括号放在字符类中以强制它们匹配:[[]
是仅包含字符[
和[]]< 的字符类/code> 是仅包含字符
]
的字符类(右括号可以通过将其放在第一个位置来放置在字符类中)。此外,由于括号在字符串文字中不会转义,因此您的代码将查找反斜杠和括号。
The brackets in
glob
are used for character classes (e.g.[a-z]
will match lowercase letters). You can put each bracket in a character class to force them being matched:[[]
is a character class containing only the character[
, and[]]
is a character class containing only the character]
(the closing bracket can be placed in a character class by putting it in the first position).Additionally, since brackets aren't escaped in string literals, your code will look for a backslash as well as a bracket.
在Python 3.4中,您可以使用
glob.escape
< /a>.In Python 3.4 you can use
glob.escape
.glob
在底层使用fnmatch
。您可以直接使用它:或者使用(非公共)
glob.glob1()
(它至少存在于Python 2.3+,包括Python 3中):这是
glob.glob1
:glob
usesfnmatch
under the hood. You could use it directly:Or using (non-public)
glob.glob1()
(it is present at least in Python 2.3+ including Python 3):Here's the implementation of
glob.glob1
:您可以使用
path.replace('[', '[[]')
让glob
正确处理任意输入路径。You could use
path.replace('[', '[[]')
to have arbitrary input paths handled byglob
correctly.glob.escape 将转义通配符。因此使用
glob.escape will escape the wildcard. Therefore use