python:使用特定目录中的glob

python:使用特定目录中的glob

我正在使用 glob 函数来加载

#make a list from pdb filles located in the same directory as this python script
pdb_list = glob.glob('*.pdb')


# do something on each pdb file
for pdb in pdb_list:
  some_variable = some_function(pdb)

我如何使用 glob 的特定路径,例如直接从与我的 python 脚本位于同一位置的某个特定子目录加载所有这些 pdb 填充,然后返回到初始目录(以产生一些输出)?

The one way that I found is to use
# change current directory to ./pdb
os.chdir("pdb")

然而,在这种情况下,一切(包括结果的保存)都将发生在包含所有初始 PDB 填充的目录中。是否有可能表明 glob 在 pdb 文件夹内查找填充但始终保留在初始位置?

答案1

glob也适用于相对路径,因此您可以简单地使用pdb/*.pdb并且它会起作用 -glob将返回相对于当前目录的结果:

>>> glob.glob('test/*.txt')
['test/c.txt', 'test/b.txt', 'test/a.txt']

如果您需要不带目录的结果,您始终可以使用它os.path.basename来获取文件名:

>>> [os.path.basename(p) for p in glob.glob('test/*.txt')]
['c.txt', 'b.txt', 'a.txt']

相关内容