首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解os.walk Python

理解os.walk Python
EN

Stack Overflow用户
提问于 2020-01-28 02:41:26
回答 1查看 114关注 0票数 0

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

我对os.path.join的使用感到困惑,下面的2或更多目录深度的代码工作得很好。

DIR_1:

文件2.txt

B= file3.txt

file1.txt

代码语言:javascript
复制
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")

但在只有一个深度的情况下,它增加了额外的'/‘。有什么办法可以避免这种情况吗?

例如,以下内容提供了:

代码语言:javascript
复制
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 1/file1.txt。

DIR_2/A/file2 2/file2.txt。类似的。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-28 02:51:33

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

代码语言:javascript
复制
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))

就这样!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59941510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档