1

我正在处理如下文件夹层次结构:

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

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

4

2 回答 2

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, '..', '..')

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

于 2012-06-05T18:27:53.650 回答
0

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

for root, dirs, files in os.walk(path, '*.txt'):
    out = open(os.path.join(root, '..', '..'), 'a')
    out.write(...)
于 2012-06-05T18:32:28.903 回答