Python Glob和方括号字符('[]') [英] Python glob and bracket characters ('[]')
问题描述
/Users/smcho/Desktop/bracket/[10,20]目录具有"abc.txt",但是当我运行此Python代码时
/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)
它返回一个空列表.
- Python的glob无法处理括号或其他字母吗?
- 有什么办法解决这个问题?
推荐答案
glob
中的括号用于字符类(例如,[a-z]
将匹配小写字母).您可以将每个括号放在一个字符类中以强制将它们匹配:
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:
path1 = "/Users/smcho/Desktop/bracket/[[]10,20[]]"
[[]
是仅包含字符[
的字符类,而[]]
是仅包含字符]
的字符类(可以将闭括号放在字符类中,方法是将其放在第一个字符中位置).
[[]
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 Glob和方括号字符('[]')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!