如何形成适用于野生字符或完全匹配的 glob?
How to form a glob that works for a wild char or exact match?
我正在使用如下语句:
input_stuff = '1,2,3'
glob(folder+'['+ input_stuff + ']'+'*')
列出以 1,2 或 3 开头的文件,而这会列出诸如 1-my-file, 2-my-file, 3-my-file 之类的文件。
如果给出了确切的文件名,这将不起作用
input_stuff = '1-my-file, 2-my-file, 3-my-file'
glob(folder+'['+ input_stuff + ']'+'*')
错误是:sre_constants.error: bad character range
更糟糕的是:
input_stuff = '1-my-'
glob(folder+'['+ input_stuff + ']'+'*')
它打印文件夹中的所有内容,例如 3-my-file 等,
是否有 glob 语句可以为两者打印文件
input_stuff = '1,2,3'
或
input_stuff = '1-my-file, 2-my-file, 3-my-file'
?
您可以使用以下内容:
input_stuff = '1,2,3'
glob(folder+'['+input_stuff+']-my-file*')
编辑:既然你在评论中说过你不能硬编码“-my-file”,你可以这样做:
input_stuff = '1,2,3'
name = "-my-file"
print glob.glob(folder+'['+input_stuff+']'+name+'*')
然后在需要时更改 "name" 变量。
括号中的glob表达式是一组字符,不是字符串列表。
您首先表达 input_stuff = '1,2,3'
等同于 '123,'
并且还将匹配以逗号开头的名称。
您的第二个表达式包含 '-'
,用于表示像“0-9A-F
”这样的字符范围,因此会出现错误。
最好完全放弃 glob,拆分 input_stuff
并使用 listdir。
import re, os
input_stuff = '1-my-file, 2-my-file, 3-my-file'
folder = '.'
prefixes = re.split(r'\s*,\s*', input_stuff) #split on commas with optional spaces
prefixes = tuple(prefixes) # startswith doesn't work with list
file_names = os.listdir(folder)
filtered_names = [os.path.join(folder, fname) for fname in file_names
if file_name.startswith(prefixes)]
我正在使用如下语句:
input_stuff = '1,2,3'
glob(folder+'['+ input_stuff + ']'+'*')
列出以 1,2 或 3 开头的文件,而这会列出诸如 1-my-file, 2-my-file, 3-my-file 之类的文件。 如果给出了确切的文件名,这将不起作用
input_stuff = '1-my-file, 2-my-file, 3-my-file'
glob(folder+'['+ input_stuff + ']'+'*')
错误是:sre_constants.error: bad character range
更糟糕的是:
input_stuff = '1-my-'
glob(folder+'['+ input_stuff + ']'+'*')
它打印文件夹中的所有内容,例如 3-my-file 等,
是否有 glob 语句可以为两者打印文件
input_stuff = '1,2,3'
或
input_stuff = '1-my-file, 2-my-file, 3-my-file'
?
您可以使用以下内容:
input_stuff = '1,2,3'
glob(folder+'['+input_stuff+']-my-file*')
编辑:既然你在评论中说过你不能硬编码“-my-file”,你可以这样做:
input_stuff = '1,2,3'
name = "-my-file"
print glob.glob(folder+'['+input_stuff+']'+name+'*')
然后在需要时更改 "name" 变量。
括号中的glob表达式是一组字符,不是字符串列表。
您首先表达 input_stuff = '1,2,3'
等同于 '123,'
并且还将匹配以逗号开头的名称。
您的第二个表达式包含 '-'
,用于表示像“0-9A-F
”这样的字符范围,因此会出现错误。
最好完全放弃 glob,拆分 input_stuff
并使用 listdir。
import re, os
input_stuff = '1-my-file, 2-my-file, 3-my-file'
folder = '.'
prefixes = re.split(r'\s*,\s*', input_stuff) #split on commas with optional spaces
prefixes = tuple(prefixes) # startswith doesn't work with list
file_names = os.listdir(folder)
filtered_names = [os.path.join(folder, fname) for fname in file_names
if file_name.startswith(prefixes)]