在python中使用walk函数

在python中使用walk函数,python,Python,我处理的文件夹层次结构如下所示: c:/users/rox/halogen/iodine/(some .txt files) c:/users/rox/halogen/chlorine/(some .txt files) c:/users/rox/inert/helium/(some .txt files) c:/users/rox/inert/argon/(some .txt files) 现在,我使用os.walk遍历文件夹并处理文件。 但问题是,如果我想在分析了卤素下的所有子文件夹后,生

我处理的文件夹层次结构如下所示:

c:/users/rox/halogen/iodine/(some .txt files)
c:/users/rox/halogen/chlorine/(some .txt files)
c:/users/rox/inert/helium/(some .txt files)
c:/users/rox/inert/argon/(some .txt files)
现在,我使用
os.walk
遍历文件夹并处理文件。
但问题是,如果我想在分析了卤素下的所有子文件夹后,生成对文件夹“卤素”的分析输出,那么我应该怎么做。。。 我使用的是:

for root,dirs,files in os.walk(path,'*.txt):
    .....
    .......[processing file]
    out.write(.....)    # writing output in the folder which we are analyzing

但是如何将输出写入后退两步的文件夹(即卤素或惰性)

在漫游之前打开输出文件

out = open(os.path.join(path, outputfilename), 'w')
然后沿着处理输入的路径走

for root,dirs,files in os.walk(path,'*.txt):
    .....
    out.write(..)
这样您就已经知道根路径了。否则,如果您确定您的路径只需后退两步

os.path.join(current_path, '..', '..')

将为您提供文件夹路径,两步后退

您可以使用正在处理的目录中的相对路径打开输出文件,如下所示:

for root, dirs, files in os.walk(path, '*.txt'):
    out = open(os.path.join(root, '..', '..'), 'a')
    out.write(...)