简体   繁体   English

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

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

I have a situation in which the directory I'm working at has many files and folders (something like that):我有一种情况,我正在处理的目录有很多文件和文件夹(类似这样):

AAA_SUBFOLDER
AAA_FILE_1
AAA_FILE_2
BBB_SUBFOLDER
BBB_FILE_1
BBB_FILE_2

So files and subfolders both starting with AAA or BBB (and so on with CCC, DDD..).所以文件和子文件夹都以AAABBB开头(等等以 CCC、DDD.. 开头)。 What I'd like to do is a python script that moves all the AAA files to the AAA subfolder and iterate this for all the files and subfolders with the same names in order to obtain something like this:我想做的是一个python 脚本,它将所有AAA文件移动到AAA子文件夹,并对所有具有相同名称的文件和子文件夹进行迭代,以获得如下内容:

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

Can you help me?你能帮助我吗? Thanks in advance!提前致谢!

this solution should work for your requirement.该解决方案应该可以满足您的要求。 steps:脚步:

  1. make sure you have python installed确保您已安装 python
  2. save script to a file (lets say main.py)将脚本保存到文件(比如说 main.py)
  3. run the saved file with 2 arguments - 1 for path you want to organize, 2 for the delimiter of the subfolder.使用 2 arguments 运行保存的文件 - 1 用于您要组织的路径,2 用于子文件夹的分隔符。 example: python main.py -p "D:\path\to\files" -d "_"例如: python main.py -p "D:\path\to\files" -d "_"

,. ,. this doesn't rearrange inner folders, only top level.这不会重新排列内部文件夹,只会重新排列顶层。

if you got any questions, I'll gladly help.如果您有任何问题,我很乐意提供帮助。

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))


This is my solution using pathlib rename;) The script as it is assume the current is the path with your files and folders.这是我使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将文件移动到恰好在Python中具有相同文件名的新文件夹中 - Move file to a new folder that happens to have the same file name in Python 写一个 function 将两个同名文件(文件扩展名不同)移动到 python 同名文件夹中 - Writing a function to move two files with the same name (with different file extensions) to a folder with the same name in python python:我可以将基于名称一部分的文件移动到具有该名称的文件夹中 - python: can i move a file based on part of the name to a folder with that name 如何在python中获取文件夹名称和文件名 - how to get a folder name and file name in python 如果已存在同名文件,则将文件移动到文件夹并重命名 - move a file to a folder and rename it if a file with the same name already exists 如何访问 python 中文件名中具有相同字符串的文件夹中的文件? - How to access files in folder with same string in file name in python? 如何使用python将具有相同名称的行移动到列中 - How to move rows with same name into columns with python Python:将文件名与同一目录中的文件夹名进行比较 - Python : Comparing file name with folder name in same directory Python 在搜索框中输入名称并在同名文件夹中查找文件 - Python input name in searchbox and find file in folder with same name Python:根据文件名的一部分将文件移动到文件夹 - Python: Move files to folder based on Part of File name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM