Python: 如何将具有特定名称的文件移动到同名文件夹中

Python: how to move a file with a certain name to a folder with the same name

我的工作目录有很多文件和文件夹(诸如此类):

AAA_SUBFOLDER
AAA_FILE_1
AAA_FILE_2
BBB_SUBFOLDER
BBB_FILE_1
BBB_FILE_2

所以文件和子文件夹都以 AAABBB 开头(以 CCC、DDD.. 依此类推)。我想做的是 python 脚本 将所有 AAA 文件移动到 AAA 子文件夹并为所有文件迭代和具有相同名称的子文件夹以获得如下内容:

AAA_SUBFOLDER
  - AAA_FILE_1
  - AAA_FILE_2
BBB_SUBFOLDER
  - BBB_FILE_1
  - BBB_FILE_2
...

你能帮帮我吗?提前致谢!

此解决方案应该可以满足您的要求。 步骤:

  1. 确保您已安装 python
  2. 将脚本保存到文件(比方说 main.py)
  3. 运行 保存的文件有 2 个参数 - 1 个用于您要组织的路径,2 个用于子文件夹的分隔符。示例:python main.py -p "D:\path\to\files" -d "_"

!!这不会重新排列内部文件夹,只会重新排列顶级文件夹。

如果您有任何问题,我很乐意提供帮助。

import os
import argparse
from pathlib import Path

def parse_args() -> tuple:
    ap = argparse.ArgumentParser()
    ap.add_argument("-p", "--path", default="./files", help="path to the folder that needs organizing")
    ap.add_argument("-d", "--delimiter", default="_", help="delimiter of file names")
    return ap.parse_args()

args = parse_args()

for filename in os.listdir(args.path):
    file_path = os.path.join(args.path, filename)
    if not os.path.isfile(file_path):
        continue
    subfolder_name = Path(filename).stem.split(args.delimiter)[0]
    subfolder_path = os.path.join(args.path,subfolder_name)
    os.makedirs(subfolder_path, exist_ok=True)
    os.rename(file_path, os.path.join(subfolder_path, filename))


这是我使用 pathlib 重命名的解决方案 ;) 假设当前脚本是您的文件和文件夹的路径。

# using pathlip
from collections import defaultdict
from pathlib import Path

TARGET_DIR = Path('.') # script dir

FILES_AND_FOLDERS = TARGET_DIR.rglob('*')

# storage with files and folders 
storage = defaultdict(list)
for blob in FILES_AND_FOLDERS:
    if blob.is_file():
        storage['files'].append(blob)
    elif blob.is_dir():
        storage['dir'].append(blob)

# for each dir check if file first 3 characters 
# match if so move by rename
    
for directory in storage['dir']:
    for file in storage['files']:
        if file.name[:3] == directory.name[:3]:
            file.rename(directory / file)
    
# you can look at shutil too