递归地使用 glob.glob 同时还利用 .format 语法
using glob.glob recursively while also utilizing .format syntax
这是我的第一个问题,我是 Python 新手。
使用 Python 3.5。
我想递归地使用 glob,并且发现这个关于递归地使用 glob 的答案非常有帮助:Use a Glob() to find files recursively in Python?
不过,我也想利用循环变量,似乎无法找出正确的语法。
这个returns一个列表就好了:
x = glob.glob(('{0}*.txt').format(some_variable))
这是我在上面链接到的 glob.glob 问题的答案提供的 "recursive" 语法,效果很好,returns 一个列表:
x = glob.glob('**/*.txt', recursive = True)
到目前为止,还不错。但是当我尝试这个时,我得到 "AttributeError: 'list' object has no attribute 'format'":
x = glob.glob('**/{0}*.txt', recursive = True).format(some_variable)
我也试过这个,它给出了 "invalid syntax" 错误:
x = glob.glob(('**/{0}*.txt').format(some_variable)), recursive = True)
我敢打赌我在最基本的意义上犯了错误,或者我不能将 .format 语法与我在这里尝试的递归版本的 glob 一起使用?我认为还有其他方法可以递归地执行此操作,但我仍然对为什么我尝试的第一种语法不起作用感到困惑。
非常感谢任何意见!谢谢!
试试这个:
x = glob.glob('**/{0}*.txt'.format(some_variable), recursive = True)
这是我的第一个问题,我是 Python 新手。
使用 Python 3.5。
我想递归地使用 glob,并且发现这个关于递归地使用 glob 的答案非常有帮助:Use a Glob() to find files recursively in Python?
不过,我也想利用循环变量,似乎无法找出正确的语法。 这个returns一个列表就好了:
x = glob.glob(('{0}*.txt').format(some_variable))
这是我在上面链接到的 glob.glob 问题的答案提供的 "recursive" 语法,效果很好,returns 一个列表:
x = glob.glob('**/*.txt', recursive = True)
到目前为止,还不错。但是当我尝试这个时,我得到 "AttributeError: 'list' object has no attribute 'format'":
x = glob.glob('**/{0}*.txt', recursive = True).format(some_variable)
我也试过这个,它给出了 "invalid syntax" 错误:
x = glob.glob(('**/{0}*.txt').format(some_variable)), recursive = True)
我敢打赌我在最基本的意义上犯了错误,或者我不能将 .format 语法与我在这里尝试的递归版本的 glob 一起使用?我认为还有其他方法可以递归地执行此操作,但我仍然对为什么我尝试的第一种语法不起作用感到困惑。
非常感谢任何意见!谢谢!
试试这个:
x = glob.glob('**/{0}*.txt'.format(some_variable), recursive = True)