2012-06-05 35 views
1

我处理类似下面的文件夹层次:使用功能走在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和处理文件,通过迭代出来的文件夹。
但问题是,如果我想分析卤素灯下所有子文件夹后生成分析输出到文件夹“卤”,那么我该怎么办......我 使用:

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

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

回答

0

可以使用从正在处理这样的目录的相对路径打开输出文件:

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

在走路前打开您的输出文件。

out = open(os.path.join(path, outputfilename), 'w') 

,然后步行路径处理您的输入

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

你已经知道的根路径这种方式。否则,如果你确定你的路线只是两步退。

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

会给你的文件夹路径,两步倒退