Compare Multiple File Name With The Prefix Of Name In Same Directory
I have multiple .png and .json file in same directory . And I want to check where the files available in the directory are of same name or not like a.png & a.json, b.png &
Solution 1:
You may try this:
import os
_, _ ,files = os.walk('.').next()
json = [f[:-5] for f in files if f.endswith('.json')]
png = [f[:-4] for f in files if f.endswith('.png')]
json_only = set(json) - set(png)
png_only = set(png) - set(json)
json_and_png = set(json) & set(png)
... etc...
Solution 2:
from pathlib import Path
print("TEST CASE::NAMING CONVENTIONS SHOULD BE START WITH GAME PREFIX ")
def get_invalid_files_from(directory: str) -> []:
dir_path = Path(r"E:\abc\\xyz")
parent_folder = dir_path.stem
files = dir_path.rglob('*')
return [str(f) for f in files if is_file_invalid(f, prefix=parent_folder)]
def is_file_invalid(file: Path, prefix: str) -> bool:
return file.suffix.lower() in ['.png', '.json'] and not file.name.startswith(prefix)
testcase = True
invalid_files = get_invalid_files_from(r'E:\abc\\xyz')
#assert not invalid_files, 'Invalid file paths:\n' + '\n'.join(invalid_files)if invalid_files :
testcase = Falseprint(r'Below given File found with invalid prefix:')
print('\n'.join(invalid_files))
if not testcase:
print("test case failed ")
else:
print("Test Case Passed ")
Solution 3:
@lenik is on the right track, I believe using sets is the easiest way to get what you want. Here's a complete and tested solution using the pathlib module that lists any png/json files that do not have a matching pair in the provided folder and all sub-folders:
defget_unpaired_files(directory: str) -> []:
dir_path = Path(directory).resolve()
json_files = get_files_without_extension(dir_path, pattern='*.json')
png_files = get_files_without_extension(dir_path, pattern='*.png')
return [str(f) for f inset(json_files) ^ set(png_files)]
defget_files_without_extension(dir_path: Path, pattern: str) -> []:
return [f.with_suffix('') for f in dir_path.rglob(pattern)]
Usage:
unpaired_files = get_unpaired_files(r'E:\abc')
if unpaired_files :
print('Unpaired file paths were found:')
print('\n'.join(unpaired_files))
Post a Comment for "Compare Multiple File Name With The Prefix Of Name In Same Directory"