如果一个文件不包含名为“过时”的子字符串,我会尝试将所有文件夹和文件从一个路径复制到另一个路径。这是我的代码:
import os
import shutil
rootdir = "C:/Old"
new_rootdir = "C:/New/"
for root, dirs, files in os.walk(rootdir):
for filename in files:
if not "obsolete" in filename:
source = root + "\\" + filename
extra_paths = source.split("\\")[1:] # strings to be merged to the new destination
destination = new_rootdir + "/".join(extra_paths)
if not os.path.exists(destination):
os.makedirs(destination) # Create the destination directory if it doesn't exist
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for directory in dirs:
source_path = os.path.join(root, directory)
destination_path = os.path.join(destination, os.path.relpath(source_path, source))
if not os.path.exists(destination_path):
os.makedirs(destination_path)
for file in files:
source_path = os.path.join(root, file)
destination_path = os.path.join(destination, os.path.relpath(source_path, source))
shutil.copy2(source_path, destination_path)
else:
shutil.copy2(source, destination)
脚本可以工作,但它为每个文件创建一个新的文件夹,上面有它的名称
C:/Old/Documents/example.txt
它正在创造一条新的道路
C:/New/Documents/example.txt/example.txt
应该是
C:/New/Documents/example.txt
如何修复此问题,使脚本不会创建具有文件名的文件夹?