1. Assumptions
- The
Sorted folder goes next to your inbox, at /Users/osamu/Documents/Sorted, so nothing new appears inside Work_Inbox. - Client names match ignoring case, underscores, hyphens and extra spaces, so
mamberth_games counts. A partial name such as corian on its own does not count. - Hidden files like
.DS_Store are ignored without comment. Files that are not PDF or DOCX are listed as skipped. - If a sorted copy already exists, it is skipped rather than overwritten. Each real run adds its rows to the end of
index.csv.
2. Script
#!/usr/bin/env python3
"""Copy invoices and deliveries from Work_Inbox into Sorted/<Client>/<YYYY-MM>/ with tidy names.
Your original files are never moved, renamed or changed."""
import csv
import re
import shutil
import unicodedata
from datetime import date
from pathlib import Path
# ---------------- SETTINGS (change these) ----------------
INBOX = Path("/Users/osamu/Documents/Work_Inbox")
OUTPUT = Path("/Users/osamu/Documents/Sorted")
INDEX_NAME = "index.csv"
CLIENTS = ["Corian Pharma", "Mamberth Games", "Zythrel Legal"]
INVOICE_KEYWORDS = ["請求書", "invoice"]
EXTENSIONS = [".pdf", ".docx"]
DRY_RUN = True # True = only show what would happen. Change to False to really copy.
# ---------------------------------------------------------
# Date patterns seen in your files: R6.11.30 (Reiwa), 2024-10-31, 2024.11.18, 20241105
REIWA = re.compile(r"(?<![A-Za-z])R(\d{1,2})\.(\d{1,2})\.(\d{1,2})(?!\d)")
WESTERN = re.compile(r"(?<!\d)(20\d\d)[-.]?(\d\d)[-.]?(\d\d)(?!\d)")
def simplify(text):
"""Lowercase and turn _ - . and runs of spaces into one space."""
return re.sub(r"[\s_.\-]+", " ", text.lower()).strip()
def find_client(text):
"""Return the first client whose name appears in the text, or None."""
simple = simplify(text)
for client in CLIENTS:
if simplify(client) in simple:
return client
return None
def find_date(text):
"""Return a date from a Reiwa or western date in the text, or None."""
m = REIWA.search(text)
if m:
year, month, day = 2018 + int(m[1]), m[2], m[3] # Reiwa 1 = 2019
else:
m = WESTERN.search(text)
if not m:
return None
year, month, day = m[1], m[2], m[3]
try:
return date(int(year), int(month), int(day))
except ValueError: # e.g. month 13: treat as no date
return None
def file_type(text):
lower = text.lower()
return "invoice" if any(k.lower() in lower for k in INVOICE_KEYWORDS) else "delivery"
def main():
if not INBOX.is_dir():
print(f"Inbox folder not found: {INBOX}")
return
read, rows, skipped = 0, [], []
# Step 1: look at each file in the inbox (not subfolders, not hidden files)
for path in sorted(INBOX.iterdir()):
if not path.is_file() or path.name.startswith("."):
continue
read += 1
name = unicodedata.normalize("NFC", path.name) # macOS can store Japanese names oddly
stem = unicodedata.normalize("NFC", path.stem)
# Step 2: work out client, date and type, or skip with a reason
if path.suffix.lower() not in EXTENSIONS:
skipped.append((name, f"not a {' or '.join(EXTENSIONS)} file"))
continue
client = find_client(stem)
if not client:
skipped.append((name, "no client name found"))
continue
day = find_date(stem)
if not day:
skipped.append((name, "no valid date found"))
continue
kind = file_type(stem)
# Step 3: build the new folder and name
new_name = f"{day.isoformat()}_{client}_{kind}_{name}"
target = OUTPUT / client / day.strftime("%Y-%m") / new_name
relative = str(target.relative_to(OUTPUT))
if target.exists():
skipped.append((name, "already sorted (copy exists, not overwritten)"))
continue
# Step 4: copy (or just report, in dry run)
if DRY_RUN:
print(f"WOULD COPY {name}\n -> {relative}")
else:
try:
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, target)
except OSError as err:
skipped.append((name, f"copy failed: {err}"))
continue
print(f"COPIED {name}\n -> {relative}")
rows.append([day.isoformat(), client, kind, name, relative])
# Step 5: add the copied files to index.csv (utf-8-sig so Excel/Numbers show Japanese)
index_path = OUTPUT / INDEX_NAME
if rows and not DRY_RUN:
is_new = not index_path.exists()
with open(index_path, "a", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
if is_new:
writer.writerow(["date", "client", "type", "original_file", "new_file"])
writer.writerows(rows)
# Step 6: summary
print()
print("--- Summary" + (" (DRY RUN: nothing was copied) ---" if DRY_RUN else " ---"))
print(f"Files read: {read}")
if DRY_RUN:
print(f"Rows written: 0 ({len(rows)} would be written to {INDEX_NAME})")
else:
print(f"Rows written: {len(rows)} (to {index_path})")
print(f"Skipped: {len(skipped)}")
for name, reason in skipped:
print(f" - {name}: {reason}")
if DRY_RUN:
print("To really copy, open this script, set DRY_RUN = False, and run it again.")
if __name__ == "__main__":
main()
3. How to run it
- Open TextEdit. Choose Format → Make Plain Text, then paste the script.
- Choose File → Save. Name it
sort_inbox.py, save it in Documents, and choose UTF-8 if TextEdit asks about encoding. If TextEdit offers to add .txt, choose Use .py. - Open Terminal and run:
python3 ~/Documents/sort_inbox.py
If macOS asks whether Terminal may access your Documents folder, click OK. This first run is a dry run: it only lists what it would do.
- If the list looks right, open the script in TextEdit, change
DRY_RUN = True to DRY_RUN = False, save, and run the same command again. - To open the results, run:
open ~/Documents/Sorted
Double-click index.csv to open it in Numbers or Excel.
4. What you should see
WOULD COPY CORIAN PHARMA invoice R6.11.30.pdf
-> Corian Pharma/2024-11/2024-11-30_Corian Pharma_invoice_CORIAN PHARMA invoice R6.11.30.pdf
WOULD COPY Mamberth Games 請求書 R6.11.30.pdf
-> Mamberth Games/2024-11/2024-11-30_Mamberth Games_invoice_Mamberth Games 請求書 R6.11.30.pdf
... (4 more)
--- Summary (DRY RUN: nothing was copied) ---
Files read: 8
Rows written: 0 (6 would be written to index.csv)
Skipped: 2
- notes for tax.txt: not a .pdf or .docx file
- sample_glossary_corian.docx: no client name found
index.csv after the real run (first lines):
date,client,type,original_file,new_file
2024-11-30,Corian Pharma,invoice,CORIAN PHARMA invoice R6.11.30.pdf,Corian Pharma/2024-11/2024-11-30_Corian Pharma_invoice_CORIAN PHARMA invoice R6.11.30.pdf
2024-11-30,Mamberth Games,invoice,Mamberth Games 請求書 R6.11.30.pdf,Mamberth Games/2024-11/2024-11-30_Mamberth Games_invoice_Mamberth Games 請求書 R6.11.30.pdf
2024-11-18,Zythrel Legal,delivery,Zythrel Legal - NDA translation - 2024.11.18 FINAL (1).docx,Zythrel Legal/2024-11/2024-11-18_Zythrel Legal_delivery_Zythrel Legal - NDA translation - 2024.11.18 FINAL (1).docx