Skip to content

Instantly share code, notes, and snippets.

@livingsilver94
Last active October 31, 2019 13:53
Show Gist options
  • Select an option

  • Save livingsilver94/77dfd9246ad5779784ce6e060a8a6a2f to your computer and use it in GitHub Desktop.

Select an option

Save livingsilver94/77dfd9246ad5779784ce6e060a8a6a2f to your computer and use it in GitHub Desktop.
Find files with same name but different extensions
#!/usr/bin/env python3
import argparse
import collections
import os
from os import path
ExtInfo = collections.namedtuple('ExtInfo', ['ext', 'path'])
arg_parser = argparse.ArgumentParser(description='Find results with same name but different extension.')
arg_parser.add_argument('path', default='.', nargs='?', help='path where to start looking')
arg_parser.add_argument('-R', '--recursive', action='store_true', help='search results recursively')
arg_parser.add_argument('-n', '--no-print', metavar='EXT', required=False, help='do not print .EXT files')
args = arg_parser.parse_args()
results = {}
def track_file(parent_dir, filename):
base_name, ext = path.splitext(filename)
if ext == '':
return
if base_name not in results:
results[base_name] = []
results[base_name].append(ExtInfo(ext, parent_dir))
if not args.recursive:
with os.scandir(args.path) as dir:
for entry in dir:
if entry.is_file():
track_file(args.path, entry)
else:
for root, _, files in os.walk(args.path):
for f in files:
track_file(root, f)
for f, infos in results.items():
if len(infos) == 1:
# This filename has just one extension
continue
for info in infos:
if info.ext == '.' + args.no_print:
continue
print(path.join(info.path, f + info.ext))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment