Python Permission Error when reading

11,965

Solution 1

You're trying to open a directory, not a file, because of the call to dirname on this line:

passwordList = open(os.path.dirname(file+'.txt'),"r")

To open the file instead of the directory containing it, you want something like:

passwordList = open(file + '.txt', 'r')

Or better yet, use the with construct to guarantee that the file is closed after you're done with it.

with open(file + '.txt', 'r') as passwordList:
    # Use passwordList here.
    ...

# passwordList has now been closed for you.

On Linux, trying to open a directory raises an IsADirectoryError in Python 3.5, and an IOError in Python 3.1:

IsADirectoryError: [Errno 21] Is a directory: '/home/kjc/'

I don't have a Windows box to test this on, but according to Daoctor's comment, at least one version of Windows raises a PermissionError when you try to open a directory.

PS: I think you should either trust the user to enter the whole directory-and-file name him- or herself --- without you appending the '.txt' to it --- or you should ask for just the directory, and then append a default filename to it (like os.path.join(directory, 'passwords.txt')).

Either way, asking for a "directory" and then storing it in a variable named file is guaranteed to be confusing, so pick one or the other.

Solution 2

os.path.dirname() will return the Directory in which the file is present not the file path. For example if file.txt is in path= 'C:/Users/Desktop/file.txt' then os.path.dirname(path)wil return 'C:/Users/Desktop' as output, while the open() function expects a file path. You can change the current working directory to file location and open the file directly.

os.chdir(<File Directory>)
open(<filename>,'r')

or

open(os.path.join(<fileDirectory>,<fileName>),'r')
Share:
11,965
OntologicalSin
Author by

OntologicalSin

Updated on June 04, 2022

Comments

  • OntologicalSin
    OntologicalSin almost 2 years
    import os
    import rarfile
    
    file = input("Password List Directory: ")
    rarFile = input("Rar File: ")
    
    passwordList = open(os.path.dirname(file+'.txt'),"r")
    

    with this code I am getting the error:

    Traceback (most recent call last):
      File "C:\Users\Nick     L\Desktop\Programming\PythonProgramming\RarCracker.py", line 7, in <module>
        passwordList = open(os.path.dirname(file+'.txt'),"r")
    PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Nick L\\Desktop'
    

    This is weird because I have full permission to this file as I can edit it and do whatever I want, and I am only trying to read it. Every other question I read on stackoverflow was regarding writing to a file and getting a permissions error.