簡體   English   中英

當我使用 shutil.move() 時,它會刪除一個文件夾

[英]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”文件夾,該文件夾是在我運行代碼后直接創建的。

有誰知道會發生什么?

提前致謝。

查看shutil.move文檔

當您嘗試在/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM