[英]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..).所以文件和子文件夹都以AAA
或BBB
开头(等等以 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:脚步:
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.