![](/img/trans.png)
[英]I cannot move files from one folder to another with shutil.move after several attempts
[英]When I use shutil.move() it deletes one folder
我在另一個文件中托管了一系列文件。 這些文件涉及各種烹飪菜餚,並存放在名為“cocina”的文件中。 我附上圖片:
我想做的是將所有名為“carnes-meat_type”的文件移動到另一個文件夾,托管在同一個地方,稱為“carnes”。 但是,當我使用shutil.move
時,我不知道為什么名稱為“carnes-anade”的文件消失了,只出現了這個文件的內容。 我添加圖像以使其更易於理解:
正如您在圖片中看到的,該文件(我稱之為“carnes”)包含所有涉及肉類類型的文件夾和 two.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()
function 搜索所有包含字符串“carnes-”的文件,並將它們移動到“carnes”文件夾,該文件夾是在我運行代碼后直接創建的。
有誰知道會發生什么?
提前致謝。
當您嘗試在/b
存在之前將/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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.