【问题标题】:Understanding os.walk Python理解 os.walk Python
【发布时间】:2020-05-13 10:35:09
【问题描述】:

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

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

DIR_1:

一个 |文件2.txt

B |文件3.txt

file1.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)。所以我不能忽视它。

【问题讨论】:

    标签: python python-3.x path


    【解决方案1】:

    您不必担心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))
    

    就是这样!

    【讨论】:

    • 在问题中添加。
    • @Pushpa 你的dirpath 在我的源代码中被称为root。随意使用它来进行您需要的任何过滤。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多