我试图遍历目录结构并创建一个类似的结构(但不完全相同)。
我对os.path.join的使用感到困惑,下面的2或更多目录深度的代码工作得很好。
DIR_1:
文件2.txt
B= file3.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 1/file1.txt。
DIR_2/A/file2 2/file2.txt。类似的。
编辑2: I还需要读取dirpath (of DIR_1)的内容,并选择相应的文本放入相应的输出文件( DIR_2)中。所以我不能忽视它。
发布于 2020-01-28 02:51:33
您不应该担心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))就这样!
https://stackoverflow.com/questions/59941510
复制相似问题