首页 > 解决方案 > 如何在 Python 中为另一个文件夹运行具有嵌套函数的函数

问题描述

我有一个 func_2 嵌套在 func_1 中,它们在不同的目录中执行操作。我当前的目录是 func_2 的目录。我正在迭代func_1目录中的文件名,但是func_2是在不同的文件夹中执行的,我该怎么办?

directory = 'directory of a childfolder containing all the ".pdb" files needed in filename'
def func_1(Chain_1):
  index_1 = 0
  for filename in os.listdir(directory): # filename(str)
    if filename.endswith(".pdb"):
      scores = []
      if index_1 <= 10:
        temp = func_2(Chain_1, filename) # func_2 execute a .cpp file in the mother folder
        scores.append(temp)
        index_1 = index_1 + 1
    else:
      continue

标签: pythonfunctiondirectorynested

解决方案


您可以在输入函数时更改工作目录。

这可以通过os 模块完成:

import os

# get the current working directory
print(os.getcwd())

# change the current working directory
os.chdir('./some/existing/folder')

# current working directory is now the new path
print(os.getcwd())

推荐阅读