Copy files from a nested folder into one directory by joining each source path’s components in the new filename. A file called overview can then keep its department or project name in the delivery, even when another folder has a file with the same short name. Review all generated paths first. The provided script detects duplicates in the planned set and writes new copies after confirmation.

This approach is for a deliberate export of independent regular files. It works for notes, simple reports, or images whose consumers are expecting a flat folder. An application bundle, a website with relative links, or a document project that refers to nearby assets needs its directory relationships. For those cases, keep the original hierarchy in an archive or include an explicit restructuring step based on the application’s format.

Give the folder names a purpose in the output

Start with a small practice folder called Project Notes. In it, create two subfolders called East Site and West Site. Give each subgroup a plain text file named overview.txt. Add the line Press check at North Gate to the East file and the line Delivery check at Service Door to the West file. Their short filenames are identical. The containing folders identify their contents. You can confirm the difference in a text editor before running any command.

Next create a document called instructions.txt directly in Project Notes. Use one short line saying that the overview files describe two separate sites. The resulting flat folder should keep this top-level name as it is and contain two distinct longer names. The exact expected output names are East Site--overview.txt, West Site--overview.txt, and instructions.txt.

The two hyphens indicate where one source component ended. This makes many paths readable at a glance, but a real folder or file can already contain those same characters. The displayed plan is the primary reference for finding a result’s source. If you need dependable reversible lookup after delivery, save the reviewed mappings with your project records. A combined filename can detect collisions in this batch without necessarily being reversible for every possible spelling.

Choose a scope and destination before copying

The script recursively visits a source directory. It prunes dot-prefixed folders and skips dot-prefixed files, symbolic links, and entries that are not regular files. It does not preserve empty folders. Check your input for excluded items before deciding whether this method covers your task. A hidden configuration directory is typically irrelevant to a delivery of overview notes. A hidden index for an existing application may be essential to that application.

Use a stable source folder whose visible contents you already recorded. If a service or another person is writing new files into the directory, stage a practice copy or wait for the export to finish. The plan is calculated before creating the destination. For a file that changes during the run, a newly written file may have different bytes from the ones you reviewed. Keep the source stable until after the comparison.

Use Python 3.9 or later, save the script below as flatten_files.py, and choose a destination beside the source folder. Its parent folder should exist and its last name should be unused. The script rejects a destination inside the source directory and stops when an output already exists. Passing separate quoted paths makes the arguments unambiguous when folder names include spaces. Python’s pathlib reference.

python3 flatten_files.py "/absolute/path/to/Project Notes" "/absolute/path/to/Flat Delivery"

Read the full mapping from relative source paths to flat destination names. Look for the two site overviews and the top-level instructions. Nothing is created until you type COPY exactly as requested. To leave the run before copying, submit an empty response. Recheck the input if the printed list includes a file you did not expect to share or omits one the recipient requested.

Test a real collision before relying on the flat set

Build a separate scratch input for this test. Put overview.txt inside a folder called North--Archive. Create another branch with a parent folder named North, a child folder named Archive, and a file with the same short name. The two different relative paths both produce North--Archive--overview.txt. The script should stop with a collision message and leave the chosen destination unused. Any mappings printed first are part of preflight and do not imply copying began.

Resolve the conflict in a reviewed staging copy by choosing component names that make both sources clear. For example, give the literal archive folder a meaningful label that does not collapse to the other path. Run the script again and check the two new mappings. If the recipient needs the exact original names and paths, include a manifest or deliver the folder structure. Choosing more meaningful names once is easier to explain than attaching arbitrary counters with no source record.

The collision comparison normalizes Unicode and applies case folding. It can catch proposed names that would conflict when moved to a filesystem treating those strings as equivalent. The code also rejects a proposed filename above its defined limit of two hundred and fifty-five UTF-8 bytes. A deeply nested hierarchy can easily produce a long flat name, especially with long multibyte labels. If the script reports one, shorten a staged name with enough description to remain traceable, or preserve the folder structure.

The script’s checks provide a practical limit for this export. Another destination platform can apply additional restrictions. For example, a cloud intake form may limit its complete upload path or disallow a character your local directory accepts. If you know where the files will land, check that service’s requirements before using the test output as a delivery policy.

Compare the byte contents and verify the labels

After the original practice plan matches expectations, type COPY and inspect the new folder. There should be three regular files at its top level. Open the two overview copies and check the site-specific lines. The North Gate line should belong to the East file, and the Service Door line to the West file. Read the top-level instructions to confirm the third file is distinct. This is a fast check for a source folder swapped before the run.

Use a byte comparison where fidelity matters. The following assumes the sample source and output paths. Update both arguments. Repeat for the West file and the instructions. A zero result means the file data compared identically. It cannot tell whether a labeled source was the correct revision in the first place.

cmp -s "/absolute/path/to/Project Notes/East Site/overview.txt" \
  "/absolute/path/to/Flat Delivery/East Site--overview.txt" \
  && echo "East overview contents match."

The copy loop opens each destination in an exclusive mode and copies the file content. Filesystem-level attributes are outside this byte-copy exercise. If you need creation dates, resource forks, permissions, or Finder tags for a later import, review those requirements and use a transfer method designed to preserve them. Many plain-text deliveries need only the data and a useful filename, which fits the behavior of this example. Python file copying.

A batch interrupted during writing can leave a destination directory with some files already present. Compare its count with the plan and treat it as an incomplete set until each expected copy is verified. When you retry after resolving an error, choose a fresh destination rather than combining attempts. Exclusive creation and a new target make it clear which run produced the files you are about to inspect.

Leave a source map the recipient can use

For a work handoff, preserve a copy of the reviewed source and output names. The source path can be relative to the exported project rather than revealing a home directory. Add a field for a real reason to return to the source, such as its approved revision date or the site that supplied it. A short map that distinguishes versions is more useful than filenames that happen to share a prefix. Save it outside the source you scan, unless you intend the map itself to be part of the next flat delivery.

Review the actual result after transfer as well. A download tool can truncate long names or rename duplicate items while keeping their content intact. If the receiver sees only an overview without the expected source label, compare the saved map and use the distinct text markers to identify which item arrived. When the rule no longer produces useful names across a larger collection, keep separate folders for those related groups. The flat pattern is most useful when the recipient can work with each delivered item independently.

Standalone copy script

# Run: python3 flatten_files.py "/path/to/source" "/path/to/new-output"
from pathlib import Path
import os
import shutil
import sys
import unicodedata

source, output = (Path(arg).resolve() for arg in sys.argv[1:])
if not source.is_dir() or output.is_relative_to(source) or output.exists():
    raise SystemExit("Choose an existing input and a new output outside it.")
plan = []
seen = set()
for root, dirs, files in os.walk(source, followlinks=False):
    base = Path(root)
    dirs[:] = sorted(d for d in dirs if not d.startswith(".") and not (base/d).is_symlink())
    for name in sorted(files):
        path = base / name
        if name.startswith(".") or path.is_symlink() or not path.is_file():
            continue
        flat = "--".join(path.relative_to(source).parts)
        key = unicodedata.normalize("NFC", flat).casefold()
        if key in seen or len(flat.encode("utf-8")) > 255:
            raise SystemExit(f"Collision or long filename: {flat}")
        seen.add(key)
        plan.append((path, flat))
        print(path.relative_to(source), "->", flat)
if not plan or input("Type COPY to create the flat set: ") != "COPY":
    raise SystemExit("Stopped.")
output.mkdir()
for path, name in plan:
    with path.open("rb") as src, (output/name).open("xb") as dst:
        shutil.copyfileobj(src, dst)

Keep relative references with the right package

Before flattening a less familiar folder, open two typical items from their original locations and look at how they find related material. A Markdown note might contain a link to a neighboring image using the image folder’s relative path. The script copies both files independently and gives them new names. Opening the copied note can then show a broken image even when both files compare byte for byte. Ask whether the recipient needs the standalone note, the image by itself, or the original relationship between them. For the third case, keep the linked note and its image in their original tree.

A similar problem can occur with a PDF collection when a separate index lists documents by their old names. In a trial delivery, update a copy of the index to use the new names and check each reference you changed. If the index uses working links that must remain intact, deliver the whole hierarchy while keeping a flat list for browsing. The site-overview example intentionally contains independent text files, so its content check is enough to verify the intended result. A larger collection benefits from one representative end-to-end opening check for each file group before you decide whether to flatten it.

References