如何解决当我使用 shutil.move() 时,它会删除一个文件夹
我在另一个文件中托管了一系列文件。这些文件涉及各种烹饪菜肴,并保存在名为“cocina”的文件中。我附上图片:
我想要做的是将所有名为“carnes-meat_type”的文件移动到另一个文件夹中,该文件夹位于同一位置,称为“carnes”。但是,当我使用shutil.move
时,我不知道为什么名称为“carnes-anade”的文件消失了,只出现了这个的内容。我添加了一张图片以使其更容易理解:
正如您在图像中看到的,该文件(我称之为“carnes”)包含所有与肉类类型相关的文件夹和两个 .txt 文件。这两个文件是在文件夹“carnes-anade”中的文件,我不明白为什么这个文件夹消失了,只有它的文件仍然存在,而我所做的唯一一件事就是移动文件夹。
我添加了我使用过的代码:
import re
import os
import shutil
for root,dirs,files in os.walk(root_path):
for dire in dirs:
if re.findall(r'carnes-',dire):
shutil.move(os.path.join(root_path,dire),os.path.join(root_path,'carnes'))
其中“root_path”指的是主文件夹,即“cocina”,这是其他美食菜肴文件夹所在的位置。我所做的是在 re.findall()
函数中搜索所有包含字符串“carnes-”的文件,并将它们移动到“carnes”文件夹中,该文件夹在我运行代码后直接创建。
有人知道会发生什么吗?
提前致谢。
解决方法
当您尝试将 /a
移动到 /b
之前 /b
存在时,/a
被简单地重命名为 /b
。之后,/c
将移入 /b
。
一个简单的解决方法是确保目标目录存在,然后再移动其他目录。
示例:
之前
cocina
├── arroces
├── carnes-ave
│ └── ave.txt
└── carnes-cabrito
└── cabrito.txt
import os
import shutil
root_path = "/Users/ptts/test/cocina"
source_dirs = [
os.path.join(root_path,item)
for item in os.listdir(root_path)
if os.path.isdir(os.path.join(root_path,item))
]
destination_dir = os.path.join(root_path,"carnes")
os.makedirs(destination_dir,exist_ok=True)
for source_dir in source_dirs:
folder_name = os.path.basename(source_dir)
if folder_name.startswith("carnes-"):
print("Moving " + source_dir + " to " + destination_dir)
shutil.move(source_dir,destination_dir)
之后
cocina
├── arroces
└── carnes
├── carnes-ave
│ └── ave.txt
└── carnes-cabrito
└── cabrito.txt
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。