1

I wouldlike to generate md5 for each file in directory but actually I have always the same problem :

Traceback (most recent call last):
  File "generate_md5.py", line 43, in <module>
    generate_dir(argument_path)
  File "generate_md5.py", line 29, in generate_dir
    with open(file, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'test.xsd'

I don't understand where is the problem ?

parser = ArgumentParser()
parser.add_argument('-idir', '--input_dir', help='directory', dest='path_dir_in')
argument_path = parser.parse_args()

    def generate_dir(argument_path):
        hash_md5 = hashlib.md5()

        for file in os.listdir(argument_path.path_dir_in):
            with open(file, "rb") as f:
                for chunk in iter(lambda: f.read(4096), b""):
                    hash_md5.update(chunk)
            print("Name :" + file)
            print(hash_md5.hexdigest())
            file_md5 = GenerateTxt()
            file_md5.write_file_txt([hash_md5.hexdigest()], file)
SayAz
  • 751
  • 1
  • 9
  • 16
AC-1994
  • 83
  • 9
  • 1
    theres surely a dupe somewhere this comes up all the time ... os.listdir only returns the filename, not its directory so you need `os.path.join(argument_path.path_dir_in,filename)` ... also you should not use `file` as a variable name as it shadows the builtin (which probably doesnt break anything but is bad form) – Joran Beasley May 20 '20 at 05:57
  • oh ok thanks you I understood ! – AC-1994 May 20 '20 at 06:08
  • "file" is a builtin? Are we talking python2 or python3? – Bobby Ocean May 20 '20 at 06:11

1 Answers1

0

Use os.list.dir to display all files and then os.path.join to open all files from directory :

def generate_dir(argument_path):
    hash_md5 = hashlib.md5()

    for filename in os.listdir(argument_path.path_dir_in):
        with open(os.path.join(argument_path.path_dir_in, filename), "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        print("Name :" + filename)
        print(hash_md5.hexdigest())
        file_md5 = GenerateTxt()
        file_md5.write_file_txt([hash_md5.hexdigest()], filename)
AC-1994
  • 83
  • 9