![](/img/trans.png)
[英]Move file to a new folder that happens to have the same file name in 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
所以文件和子文件夾都以AAA
或BBB
開頭(等等以 CCC、DDD.. 開頭)。 我想做的是一個python 腳本,它將所有AAA
文件移動到AAA
子文件夾,並對所有具有相同名稱的文件和子文件夾進行迭代,以獲得如下內容:
AAA_SUBFOLDER
- AAA_FILE_1
- AAA_FILE_2
BBB_SUBFOLDER
- BBB_FILE_1
- BBB_FILE_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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.