給定的目錄結構是這樣的:
$ ls /tmp/stacktest
\textures
\textures\actors\bear
fur.png
\textures\actors\bear\fur2.png
下面的Python腳本會變成這樣:
$ ls /tmp/stackdest
textures/actors/bear
fur.png
fur2.png
Python腳本:
from os import walk
import os
# TODO - Change these to correct locations
dir_path = "/tmp/stacktest"
dest_path = "/tmp/stackdest"
for (dirpath, dirnames, filenames) in walk(dir_path):
# Called for all files, recu`enter code here`rsively
for f in filenames:
# Get the full path to the original file in the file system
file_path = os.path.join(dirpath, f)
# Get the relative path, starting at the root dir
relative_path = os.path.relpath(file_path, dir_path)
# Replace \ with/to make a real file system path
new_rel_path = relative_path.replace("\\", "/")
# Remove a starting "/" if it exists, as it messes with os.path.join
if new_rel_path[0] == "/":
new_rel_path = new_rel_path[1:]
# Prepend the dest path
final_path = os.path.join(dest_path, new_rel_path)
# Make the parent directory
parent_dir = os.path.dirname(final_path)
mkdir_cmd = "mkdir -p '" + parent_dir + "'"
print("Executing: ", mkdir_cmd)
os.system(mkdir_cmd)
# Copy the file to the final path
cp_cmd = "cp '" + file_path + "' '" + final_path + "'"
print("Executing: ", cp_cmd)
os.system(cp_cmd)
該腳本讀取dir_path
中的所有文件和文件夾,並在dest_path
下創建新的目錄結構。確保你不要把dest_path
放在dir_path
之內。
德文,如果下面的解決方案有效,你可以讓這個知道。也許通過投票回答。 –
德文,做了這個解決方案的工作還是你需要幫助來實現你的目標? –
爲什麼在目錄名稱中有反斜槓? –