Different filenames, identical contents? Finding duplicates without deleting anything. — cover illustration

Different filenames, identical contents? Finding duplicates without deleting anything.


Do what you can first.

List files with the same content using Python. Distinguishes files with the same name and does not delete them.

For those who want to run small Python scripts on Mac. There is a practice file and a command->result confirmation procedure.

Table of contents of this article

"report.txt" and "report-copy.txt". You can't tell if the contents are the same just by looking at the name.

It's a pain to open them one by one and compare them. However, I don't feel comfortable deleting it just because the name seems like a copy.

This time I tried a small tool to list files with identical contents without deleting them. The test mixes identical files with different names and different files with the same name, to see whether it distinguishes them.

This is not an experience of organizing folders in real life, but an experiment conducted with 4 files for this article. The editing agent runs the code on Mac/Python 3.14 and verifies that the detection results and the original file remain unchanged.

I would like to compare the contents rather than the file name.

The following folder has been prepared. Since it is in a ZIP, you can try it under the same conditions.

sample/
├── a/
│   └── report.txt         中身:same data
├── b/
│   ├── report-copy.txt    中身:same data
│   └── report.txt         中身:other data
└── note.txt               中身:unique

Report.txt in a and report-copy.txt in b have the same content. On the other hand, two report.txt files with the same name have different contents.

It reads each file, compiles candidates based on the file size and hash value called SHA-256, and compares the candidates even in bytes. A hash value is a value calculated from the contents. This time, I'm using it as a clue to find candidates.

When I tried it, I found two with different names.

In the execution result, only two items with the same content are grouped together. Files with the same name but different contents were not mixed.

{
  "duplicate_groups": [
    ["sample/a/report.txt", "sample/b/report-copy.txt"]
  ],
  "errors": []
}

This is the result from the practice folder. The beginning of each path depends on where you saved it. The Raw log during execution is also available.

From here, let's work together.

These instructions are for Mac. Copy only the “Command to run” blocks and press Enter after each command. Do not type the result blocks. The % and $ symbols at the start of a terminal line are prompts, so they are not included in the commands here.

1. Download practice files

Download practice ZIP

  1. Click the link and save. Normally, go to "Downloads" in Finder.
  2. Double-click the ZIP to extract it. If your browser is already expanded, use that folder.
  3. Open the folder and locate find_duplicates.py and sample. You are ready when both are in the same folder.

There is no problem if the folder name becomes something like "duplicate-kit 2". In the next step, specify the actual folder by dragging it.

2. Open a terminal and move to where you want to work

  1. Press ⌘+Space, type "Terminal" and press Enter.
  2. Type cd in Terminal, with one space after cd. Do not press Enter yet.
  3. Drag the folder itself containing find_duplicates.py from Finder into Terminal.
  4. Press Enter when the folder location is entered.

You will see something like cd /Users/自分の名前/Downloads/duplicate-kit. This is only an example; do not copy it as your own path. A successful directory change usually produces no message.

Command to run

pwd

Example of results displayed

/Users/自分の名前/Downloads/duplicate-kit

Your current location will be displayed. You can use the name and save location of your own environment.

Command to run

ls -1

Example of results displayed

find_duplicates.py
sample

If you see both find_duplicates.py and sample, proceed to the next step. If you can't see it, select the folder again in step 2. The order and presence of other files does not matter.

3. Check if you can use Python

Command to run

python3 --version

Example of results displayed

Python 3.14.7

Check the display starting with Python 3. This time I verified it with 3.14.7. No additional libraries need to be installed.

command not found/Python is not installed
  1. Download a compatible stable macOS installer from Python official page for macOS.
  2. Open the .pkg and follow the instructions to install.
  3. Reopen the terminal, move the folder in step 2, and thenpython3 --versionRerun.

How to installofficial procedureBased on. This time, we have not verified the UI operation itself for a new installation.

4. Explore the practice folder

The final argument, sample, is the folder to scan. The program also checks its a and b subfolders.

Command to run

python3 find_duplicates.py sample

Result of extracting the distribution ZIP and running it

{
  "duplicate_groups": [
    [
      "sample/a/report.txt",
      "sample/b/report-copy.txt"
    ]
  ],
  "errors": []
}

If these two appear in the same square brackets, a group with the same content has been found. Since errors is empty, there are no read errors for this target.

5. Take a look at the detected contents yourself

cat displays the contents of a text file. Here, use it only with the practice text files.

Command to run

cat sample/a/report.txt

Example of results displayed

same data

This is the first content.

Command to run

cat sample/b/report-copy.txt

Example of results displayed

same data

The second one has the same content. Even if the names are different, you can see why they are in the same group.

Command to run

cat sample/b/report.txt

Example of results displayed

other data

Even though they have the same name, report.txt, the contents are different, so they are not included in the detection group.

The practice is now complete.If only two files with the same contents are found and you can check the contents with cat, it is a success.

6. Specify your own folder (advanced)

Create a new folder in Finder and copy the file you want to check with ⌘C → ⌘V inside the new folder. Try it with a few files first.

  1. In Terminal, type python3 find_duplicates.py , including a space at the end.
  2. From Finder, drag the folder you want to search.
  3. Once the path is entered, press Enter.

For example, the screen will look like this: Do not use the path below; replace it with your own folder.

Command to run

python3 find_duplicates.py "/Users/自分の名前/Documents/確認用フォルダ"

Example of results displayed

{
  "duplicate_groups": [],
  "errors": []
}

This is an example where there are no duplicates. If found, the file locations will be arranged in the same manner as in step 4. There is no display while the scan is in progress, and the results will be displayed once the scan is complete. Large folders take time.

7. If you want to keep the results (optional)

Once you've verified that it works well in the folder you want to examine, you can also save the results to a file. Let's try it with a sample first.

Command to run

python3 find_duplicates.py sample > duplicate-report.json

Example of results displayed

(画面には何も表示されません)

> specifies to save to a file instead of displaying on screen. If there is a report with the same name, it will be overwritten, so if you want to keep it, please use a different name. The original scanned file remains unchanged.

Command to run

cat duplicate-report.json

Example of results displayed

{
  "duplicate_groups": [
    [
      "sample/a/report.txt",
      "sample/b/report-copy.txt"
    ]
  ],
  "errors": []
}

If the same content as in step 4 is displayed, the file has been saved. Save the report outside of the folder you are examining.

When it stops/When the result is different

  • can't open file ...find_duplicates.py: Return to step 2 and check whether the program's filename appears in the output of ls -1.
  • 対象フォルダがありません: The specified folder was not found. Drag the folder again as shown in step 6.
  • duplicate_groups: [] and errors: [] mean no duplicates were found among the files checked. See the next section for what is included in the scan.
  • If errors contains entries, those files could not be checked. Inspect the listed paths and permissions. Do not treat this as a complete scan of every file.

Just because it shows up in the results doesn't mean it's an unnecessary copy. This code does not delete or move, but only displays a list for confirmation.

For those who want to see the contents of the distribution code

See the executed code
import os, sys, hashlib, json, filecmp
from pathlib import Path
from collections import defaultdict
root = Path(sys.argv[1] if len(sys.argv)>1 else 'sample')
if not root.is_dir():
    raise SystemExit('対象フォルダがありません')
groups = defaultdict(list)
errors = []
for folder, dirs, files in os.walk(root, followlinks=False):
    dirs[:] = sorted(d for d in dirs if not d.startswith('.') and not (Path(folder)/d).is_symlink())
    for name in sorted(files):
        p = Path(folder)/name
        if name.startswith('.') or p.is_symlink() or not p.is_file():
            continue
        try:
            h = hashlib.sha256()
            with p.open('rb') as f:
                for chunk in iter(lambda: f.read(1024*1024), b''):
                    h.update(chunk)
            groups[(p.stat().st_size,h.hexdigest())].append(p)
        except OSError as e:
            errors.append({'file':str(p),'error':str(e)})
result=[]
for candidates in groups.values():
    if len(candidates)<2: continue
    first=candidates[0]
    try:
        if all(filecmp.cmp(first,p,shallow=False) for p in candidates[1:]):
            result.append([str(p) for p in candidates])
    except OSError as e:
        errors.append({'file':str(first),'error':str(e)})
print(json.dumps({'duplicate_groups':result,'errors':errors},ensure_ascii=False,indent=2))

It looks a little different from the same photo.

This code finds files whose contents are identical byte for byte. Re-saving the same photo as a JPEG, or changing only its metadata, may prevent it from being detected as a duplicate.

There is no function to search for similar photos. Also, since all large files are read, it takes time if there are many targets. It seems best to start with a small confirmation folder.

Hidden files/folders and symbolic links are not covered. Files that cannot be read will appear in errors. If you edit the target file during execution, the results will be unstable, so check in a folder that is not in use.

Make it clear before erasing it.

What I created this time is not a tool that will do all the cleaning. This reduces the hassle of opening and checking to see if they are the same.

Before thinking about what to keep, first figure out what overlaps. I think that alone will make it easier to decide what to do next.

For tidier filenames as well, see Article about changing names all at once in Finder on Mac. I want to keep removing these small hassles, one at a time.

Reference: Python official hashlib explanation. I verified the detection results by running the downloadable sample.

Want to check notebooks or machine-learning data too?Three Python tools for splitting, evaluating and publishing data brings together synthetic browser demos and GitHub links.