Рекурсивный поиск md5 файлов в каталоге в python

Я хочу найти md5sum файлов, начинающихся с «10» (может быть exe, doc, pdf и т. д.), следовательно, не проверяя расширение файла, а только две начальные цифры. Пока у меня есть скрипт для обхода каталога и распечатки всех таких файлов, но я не смог распечатать контрольную сумму для каждого из них:

def print_files(file_directory, file_extensions=['10']):                          
''' Print files in file_directory with extensions in file_extensions, recursively. '''

# Get the absolute path of the file_directory parameter                               
  file_directory = os.path.abspath(file_directory)                                      

# Get a list of files in file_directory                                               
  file_directory_files = os.listdir(file_directory)                                     

# Traverse through all files                                                          
  for filename in file_directory_files:                                                 
    filepath = os.path.join(file_directory, filename)                                 

    # Check if it's a normal file or directory                                        
    if os.path.isfile(filepath):                                                      

        # Check if the file has an extension of typical video files
        for file_extension in file_extensions:                     
            # Not a reqd file, ignore                              
            #if not filepath.endswith(file_extension):             
            if not filename.startswith(file_extension) or len(filename) != 19:
                continue                                                      

            # We have got a '10' file!                  
            print_files.counter += 1                                          


            ## TRYING TO READ AND PRINT MD5 USING HASHLIB/ DOESNT WORK###
            hasher = hashlib.md5()                                            
            with open(filename, 'rb') as afile:                               
               buf = afile.read(65536)                                        
               while len(buf) > 0:                                            
                   hasher.update(buf)                                         
                   buf = afile.read(65536)                                    


            # Print it's name                                                 
            print('{0}'.format(filepath))                                     
            print hasher('{0}.format(filepath)').hexdigest() 
            print '\n'                                       
    elif os.path.isdir(filepath):                            
        # We got a directory, enter into it for further processing
        print_files(filepath)   
if __name__ == '__main__':                                                                

 # Directory argument supplied             
  if len(sys.argv) == 2:                                                        
    if os.path.isdir(sys.argv[1]):                                            
        file_directory = sys.argv[1]                                          
    else:                                                                     
        print('ERROR: "{0}" is not a directory.'.format(sys.argv[1]))         
        exit(1)                                                               
else:                                                                         
    # Set file directory to CWD                
    file_directory = os.getcwd()                                              

print('\n -- Looking for Required Files in "{0}" --   \n'.format(file_directory))

# Set the number of processed files equal to zero                             
print_files.counter = 0                                                       

# Start Processing                                                            
print_files(file_directory)                                                   

# We are done. Exit now.   

'


person Quick Silver    schedule 14.04.2015    source источник
comment
Что не работает? Выдает ли это исключение? Дать неверный результат? Какие?   -  person John Kugelman    schedule 14.04.2015
comment
Что не работает - вы получаете ошибку? Можете ли вы показать нам, что происходит?   -  person Tom Dalton    schedule 14.04.2015
comment
В нем говорится: -- Поиск необходимых файлов в /home/Downloads/10/ -- Трассировка (последний последний вызов): Файл list-files.py, строка 82, в ‹module› print_files(file_directory) Файл list-files. py, строка 59, в print_files print_files(filepath) Файл list-files.py, строка 46, в print_files с open(filename, 'rb') в качестве файла: IOError: [Errno 2] Нет такого файла или каталога: '1016328298791839266'   -  person Quick Silver    schedule 14.04.2015
comment
В то же время, если я удалю часть ниже, ## ПОПЫТКА ПРОЧИТАТЬ И ПЕЧАТЬ MD5 ИСПОЛЬЗОВАНИЕ HASHLIB/ НЕ РАБОТАЕТ ###, код распечатывает каждый файл   -  person Quick Silver    schedule 14.04.2015


Ответы (3)


Я бы рекомендовал вам не решать это рекурсивно, а вместо этого использовать os.walk() для обхода структуры каталогов. Следующий код может быть телом вашей функции print_files.

file_directory = os.path.abspath(file_directory)
paths_to_hash = []

for root, dirs, filenames in os.walk(file_directory, topdown=False):
    for i, dir in enumerate(dirs):
        for filename in filenames[i]:
            if filenames[:2] == '10':
                paths_to_hash += [os.path.abspath('{0}/{1}/{2}'.format(root, dir, filename)]

for path in paths_to_hash:
    hash = hashlib.md5(open(path, 'rb').read()).digest())
    print 'hash: {0} for path: {1}'.format(hash, path)
person Matt Davidson    schedule 14.04.2015
comment
Поэтому я планирую расширить этот подход таким образом, чтобы передавать текстовый файл, содержащий md5, и возвращать только те имена файлов, md5 которых присутствуют в текстовом файле. Любой указатель. - person Quick Silver; 15.04.2015

Строка, печатающая хэш, должна быть:

print('{0}'.format(hasher.hexdigest()))
person CristiFati    schedule 14.04.2015
comment
Строка: с открытым (имя файла, 'rb') как файл: заменить имя файла на путь к файлу. - person CristiFati; 14.04.2015

Исправил с этой строкой

print hashlib.md5(open('{0}'.format(filepath)).read()).hexdigest()

Я не читал файл, а просто передавал hashlib.md5. Спасибо, Мэтт, за понимание.

person Quick Silver    schedule 14.04.2015
comment
Если вы нашли мой ответ полезным, пожалуйста, оставьте этот комментарий под ответом и проголосуйте за него. Спасибо. - person Matt Davidson; 14.04.2015