تحويل أسماء الملفات إلى حروف صغيرة في Python مفيد عندما تستقبل صورًا أو مستندات بأسماء غير متناسقة. يحول المثال My File-Report.JPG إلى my_file_report.jpg، ويستبدل مجموعات المسافات والشرطات بشرطة سفلية واحدة. يعمل على الملفات العادية الموجودة مباشرة في مجلد تختاره، ويترك المجلدات والروابط الرمزية والملفات المخفية. المعاينة هي الوضع الافتراضي؛ ترى كل اسم قديم وجديد قبل السماح بأي تغيير.
أوامر التجهيز والتشغيل
python normalize_files.py demo-files
# Review the printed plan first:
python normalize_files.py demo-files --apply --log rename-normalized.jsonlملف مشترك للعمليات وملف صغير للتشغيل
احفظ الجزء الأول باسم safe_rename.py والثاني باسم normalize_files.py في مجلد الأدوات، واجعل demo-files مجلد بيانات منفصلًا بجواره. يستخدم درس ترقيم الملفات المحرك نفسه بدل تكرار منطق منع التصادم والسجل. لا تضع السكربت داخل المجلد الذي يعيد تسميته، وإلا يصبح ملف البرنامج نفسه ضمن المرشحين. لا نستخدم chdir لأن تغيير مجلد العمل يربك المسارات والسجلات في التطبيقات الكبيرة.
بناء خطة ثابتة ومعالجة الأسماء المتشابهة
ترتب build_plan الملفات ترتيبًا واضحًا قبل توليد الأسماء، وتحجز الأسماء الجديدة باستخدام casefold للمقارنة المحافظة بين أنظمة الملفات. إذا تحول My File.txt وmy-file.txt إلى الاسم نفسه، تحصل الثانية على لاحقة رقمية بدل الكتابة فوق الأولى. كما تحجز أسماء المجلدات والعناصر المستبعدة. تحتفظ الدالة بالامتداد الأخير بحروف صغيرة؛ في أرشيف مثل data.tar.gz تبقى tar جزءًا من الاسم، ولا تدعي الدالة فهم كل امتداد مركب.
الكود: safe_rename.py
from pathlib import Path
import json
import os
import re
import uuid
def normalized_name(path, index):
stem = re.sub(r"[\s-]+", "_", path.stem.strip().lower()).strip("._") or "file"
return stem + path.suffix.lower()
def numbered_name(path, index):
return f"item_{index:03d}{path.suffix.lower()}"
def build_plan(folder, name_function):
root = Path(folder).resolve(strict=True)
if not root.is_dir():
raise NotADirectoryError(root)
entries = sorted(root.iterdir(), key=lambda p: (p.name.casefold(), p.name))
files = [p for p in entries if p.is_file() and not p.is_symlink() and not p.name.startswith(".")]
reserved = {p.name.casefold() for p in entries if p not in files}
plan = []
for index, source in enumerate(files, 1):
name = name_function(source, index)
if not name or Path(name).name != name or name in {".", ".."}:
raise ValueError("Invalid target name")
candidate = name
count = 1
while candidate.casefold() in reserved:
candidate = f"{Path(name).stem}_{count}{Path(name).suffix}"
count += 1
reserved.add(candidate.casefold())
if candidate != source.name:
plan.append((source, root / candidate))
return plan
def move_without_replace(source, target):
# Same-directory regular files only. If hard links are unsupported, fail without overwriting.
os.link(source, target, follow_symlinks=False)
source.unlink()
def apply_plan(plan, log_path):
if not plan:
return
root = plan[0][0].parent
log_path = Path(log_path).absolute()
if log_path.parent.resolve() == root:
raise ValueError("Keep the log outside the input folder")
staged = [(source, root / (".gc-rename-" + uuid.uuid4().hex), target) for source, target in plan]
for source, temporary, target in staged:
if source.is_symlink() or not source.is_file() or source.parent != root or target.parent != root:
raise ValueError("Unexpected source state")
with log_path.open("x", encoding="utf-8") as log:
def record(event, source, target):
log.write(json.dumps({"event": event, "from": str(source), "to": str(target)}, ensure_ascii=False) + "\n")
log.flush()
os.fsync(log.fileno())
for source, temporary, target in staged:
record("planned", source, temporary)
record("destination", temporary, target)
# Stage first to support swaps and case-only renames on case-insensitive file systems.
for source, temporary, target in staged:
move_without_replace(source, temporary)
record("staged", source, temporary)
for source, temporary, target in staged:
move_without_replace(temporary, target)
record("completed", temporary, target)
الكود: normalize_files.py
import argparse
from safe_rename import build_plan, normalized_name, apply_plan
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("folder")
parser.add_argument("--apply", action="store_true")
parser.add_argument("--log", default="rename-normalized.jsonl")
args = parser.parse_args()
plan = build_plan(args.folder, normalized_name)
for source, target in plan:
print(source.name, "->", target.name)
if args.apply:
apply_plan(plan, args.log)
else:
print("Preview only; no files changed")
لماذا توجد مرحلة أسماء مؤقتة؟
قد يختلف الاسم الجديد عن القديم في حالة الحروف فقط، وقد يتبادل ملفان اسمين موجودين. لذلك تنقل مرحلة التنفيذ الملفات المتغيرة أولًا إلى أسماء مؤقتة فريدة داخل المجلد، ثم إلى الأسماء النهائية. يستخدم النقل رابطًا صلبًا ثم إزالة الاسم المصدر، بحيث يرفض إنشاء اسم هدف موجود بدل استبداله كما قد تفعل rename على بعض الأنظمة. إذا كان نظام الملفات لا يدعم hard links، يتوقف التنفيذ؛ لا يوجد مسار بديل يكتب فوق الملفات.
السجل والتعامل مع التنفيذ الجزئي
ينشئ –log ملف JSONL جديدًا بالنمط x خارج مجلد الإدخال، ويرفض استبدال سجل موجود. يسجل الخطة ثم اكتمال كل مرحلة مع المسارات، ويكتب السجل قبل بدء التغيير. هذه ليست معاملة ذرية: فشل القرص أو صلاحية أو تغيير متزامن قد يترك بعض الأسماء مؤقتة أو نهائية. احتفظ بالسجل والنسخة الاحتياطية، وتوقف عن تعديل المجلد حتى تراجع آخر عملية مكتملة. لا تشغل السكربت بالتوازي مع برنامج يعيد تسمية الملفات نفسها.
تشغيل المعاينة ثم التطبيق
أنشئ مجلد تجربة يحتوي نسخًا غير مهمة، وشغل python normalize_files.py demo-files. افحص الناتج وتأكد من أنه لا يغير محتوى الملفات أو يتوسع داخل المجلدات. عند قبول الخطة أضف –apply واختر سجلًا جديدًا. احفظ تجزئات أو أحجام عينات قبل العملية وقارنها بعدها، وجرب حالة أسماء متشابهة ومجلد يحمل اسم هدف. لا تتجاوز خطأ FileExistsError بحذف الهدف؛ افهم مصدر التعارض وأعد بناء الخطة.
حدود التطبيع والرجوع عن الأسماء
البرنامج لا يترجم العربية إلى لاتينية ولا يضمن أن كل اسم صالح لكل خدمة سحابية؛ يحافظ على النصوص عدا قواعد التطبيع المحددة. راجع قواعد Windows أو الخادم الذي ستنقل إليه الملفات إذا احتاجت أسماء محمولة بين الأنظمة. تغيير الاسم قد يكسر روابط تعتمد عليه، ولذلك اختبر مرجع الصور أو المسارات في مشروعك. الرجوع يحتاج تطبيق الخريطة بالعكس بعد التأكد من عدم وجود تعارض، وليس إعادة تشغيل دالة التطبيع؛ فالعملية لا تحفظ الأسماء الأصلية في الاسم الجديد.






