Skip to content

Instantly share code, notes, and snippets.

@Jonarzz
Last active July 17, 2016 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jonarzz/a5fcedd10f298439acca53dc2bee9203 to your computer and use it in GitHub Desktop.
Save Jonarzz/a5fcedd10f298439acca53dc2bee9203 to your computer and use it in GitHub Desktop.
"""
https://github.com/qofnaught/wykop_wyzwaniepython/tree/master/edycja1
Otrzymujesz katalog zawierający 1000 plików o losowych nazwach które są wypełnione
3 losowymi znakami. Twoim zadaniem jest:
Wersja łatwa
- Odczytać rok i miesiąc modyfikacji pliku
- skopiowac wszystkie pliki z danego roku do do jednego katalogu a poźniej to samo dla miesięcy
Wersja trudna
- To co łatwa
- Znaleźć wszystkie duplikaty, najpóźniej zmodyfikowany przenieść
do katalogu jak w wersji łatwej, a pozostałe przenieść do katalogu o nazwie "duplikaty"
Założenia:
- bezwzględna ścieżka do katalogu źródłowego podana jest jako argument
- bezwzględna ścieżka do katalogu docelowego podana jest jako argument
"""
import sys
import os
import hashlib
import shutil
from datetime import datetime
USAGE_STRING = ('Sposób użycia:\n'
'python file_sorter.py <bezwzględna ścieżka katalogu źródłowego>'
' <bezwzględna ścieżka katalogu docelowego> <opcje>\n'
'Na przykład: python file_sorter.py C:/dir C:/target/dir --del\n'
'Opcjonalne argumenty:\n '
'--del - usuń katalog źródłowy po zakończeniu przenoszenia.')
DIPLICATES_SUBDIR = 'duplikaty'
def directories_from_args(args):
return args[1].strip('/'), args[2].strip('/')
def filedirs_from_source_dir(source_dir):
return ['/'.join([source_dir, x]) for x in os.listdir(source_dir)]
def create_non_duplicate_dict(file_dirs_sorted_by_date):
non_duplicate_dict = {} # { filedir: hash }
for filedir in file_dirs_sorted_by_date:
filehash = hashlib.sha256(open(filedir, 'rb').read()).digest()
if filehash not in non_duplicate_dict.values():
non_duplicate_dict[filedir] = filehash
return non_duplicate_dict
def create_dir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
def move_file_to_duplicate_directory(file_dir, destination_dir):
duplicate_filename = file_dir.split('/')[-1]
shutil.move(file_dir, '{}/{}/{}'.format(destination_dir, DIPLICATES_SUBDIR, duplicate_filename))
def move_file_to_dest_directory(file_dir, destination_dir):
modification_date = datetime.fromtimestamp(os.path.getmtime(file_dir))
year_month_dir = '{}/{}/{}'.format(destination_dir, modification_date.year, modification_date.month)
create_dir(year_month_dir)
filename = file_dir.split('/')[-1]
shutil.move(file_dir, '{}/{}'.format(year_month_dir, filename))
if __name__ == "__main__":
if len(sys.argv) < 3:
print(USAGE_STRING)
quit()
source_directory, destination_directory = directories_from_args(sys.argv)
filedirs_sorted_by_date = sorted(filedirs_from_source_dir(source_directory),
key=lambda e: -os.path.getmtime(e))
non_duplicate_dict = create_non_duplicate_dict(filedirs_sorted_by_date)
duplicate_dirs = [x for x in filedirs_sorted_by_date if x not in non_duplicate_dict.keys()]
create_dir(destination_directory)
create_dir('{}/{}'.format(destination_directory, DIPLICATES_SUBDIR))
for directory in duplicate_dirs:
move_file_to_duplicate_directory(directory, destination_directory)
for directory in non_duplicate_dict.keys():
move_file_to_dest_directory(directory, destination_directory)
if len(sys.argv) == 4:
if sys.argv[3] == '--del':
os.rmdir(source_directory)
@jmolinski
Copy link

jmolinski commented Jul 17, 2016

Lines 25 & 34 & 74: don't reinvent the wheel! :) Use something like argparse or click to deal with command line arguments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment