IsADirectoryError: [Errno 21] Is a directory: '.upm'

Viewed 3991

This is the code where i think the error might be occurring, i have read the post about eliminating the error but unable to form the code.

while True:
    files=os.listdir(".")
    #print(files)
    # Get the MD5 hash for each -- use a for loop to process each file
    for file_name in files:


        with open(file_name , "rb") as fp:


            file_content = fp.read()
            md5 = hashlib.md5(file_content).hexdigest()


        # should we compare the checksums too? XXXXXXXXX


        # check for differences between new scan and old scan.
        if not file_name in baseline.keys():
            # print the name of any new files
        print("new file detected!", file_name)

The error specifically is:

Traceback (most recent call last): File "main.py", line 31, in with open(file_name , "rb") as fp: IsADirectoryError: [Errno 21] Is a directory: '.upm'

It'll be of great help if someone can help with the correct code.

2 Answers

you are opening a folder or a directory as a file, which is leading to that error. It can be fixed by replacing files=os.listdir(".") with files = [i for i in os.listdir() if os.path.isfile(i)] This will remove that error.

while True:
    files=[i for i in os.listdir() if os.path.isfile(i)]
    #print(files)
    # Get the MD5 hash for each -- use a for loop to process each file
    for file_name in files:


        with open(file_name , "rb") as fp:


            file_content = fp.read()
            md5 = hashlib.md5(file_content).hexdigest()


        # should we compare the checksums too? XXXXXXXXX


        # check for differences between new scan and old scan.
        if not file_name in baseline.keys():
            # print the name of any new files
        print("new file detected!", file_name)

i wonder how @jaychandra answer is complete answer while it's not going to check files in subfolders, also there is no point of hashing file if you are going to have just compare files names.

files=os.listdir(".")
for root, dirs, files in os.walk('.'):
    for file_ in files:
        with open(os.path.join(root, file_) , "rb") as fp:
            file_content = fp.read()
            md5 = hashlib.md5(file_content).hexdigest()

        if not md5 in baseline.keys():
            print("new file detected or file has been changed!", file_)

what i did is , it's going to hash all files in all subfolders also. and checks if new file has been added or previous file has be changed.

Related