繁体   English   中英

理解 os.walk Python

[英]Understanding os.walk Python

我正在尝试遍历目录结构并创建一个类似的结构(但不完全相同)。

我对 os.path.join 的使用感到困惑,以下具有 2 个或更多目录深度的代码完美运行。

目录_1:

一个 | 文件2.txt

乙 | 文件3.txt

文件1.txt

inputpath = DIR_1
outputpath = DIR_2
for dirpath, dirnames, filenames in os.walk(inputpath):
    structure = os.path.join(outputpath, dirpath[len(inputpath):])
        for f1 in filenames:
        f = os.path.splitext(f1)[0]
        path = structure + '/' + f
        print ("The path is: ", path)
        file1 = path + '/' + f1
        print ("The file path is: ", file1)
        file_dir = dirpath + '/' + f1;
        print ("The file dir path is: ", file_dir)
        print ("\n")

但是在只有一层深度的情况下,它会添加额外的“/”。 有没有办法避免这种情况?

例如以下给出:

The path is:  DIR_2//file1
The file path is:  DIR_2//file1/file1.txt
The file dir path is:  DIR_1/file1.txt


The path is:  /A/file2
The file path is:  /A/file2/file2.txt
The file dir path is:  DIR_1/A/file2.txt


The path is:  /B/file3
The file path is:  /B/file3/file3.txt
The file dir path is:  DIR_1/B/file3.txt

编辑1:

输出目录 DIR_2 结构类似于原始 Dir_1 但不完全相同。

DIR_2 应该有额外的一级目录文件名; 例如,而不仅仅是

DIR_2/file1.txt

它应该是

DIR_2/file1/file1.txt。

DIR_2/A/file2/file2.txt。 相似地。

编辑2:我还需要读取dirpath (DIR_1)的内容并选择相关文本放入相应的输出文件(DIR_2)。 所以我不能忽视它。

您不应该担心dirpath ,仅使用它来获取原始文件,所有信息以重新创建您在dirnames已有的目录结构。 重新创建文件结构的代码如下所示:

for root, dirs, files in os.walk( input_path ) :
    offset = len(input_path)
    if len(root) > len(input_path) :
        offset += 1   # remove an extra leading separator

    relative_path = root[offset:]

    for d in dirs :  # create folders
        os.mkdir( os.path.join( output_path, relative_path, d )


    for f in files : # copy the files
        shutil.copy( os.path.join( root, f),
                     os.path.join( output_path, relative_path, f))

就是这样!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM