阅读时出现Python权限错误

Ont*_*Sin 2 python windows permissions file-permissions python-3.x

import os
import rarfile

file = input("Password List Directory: ")
rarFile = input("Rar File: ")

passwordList = open(os.path.dirname(file+'.txt'),"r")
Run Code Online (Sandbox Code Playgroud)

与此代码,我得到错误:

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'
Run Code Online (Sandbox Code Playgroud)

这很奇怪,因为我对该文件拥有完全的权限,因为我可以编辑该文件并执行我想做的任何事情,而我只是在尝试读取它。我在stackoverflow上阅读的所有其他问题都与写入文件和获得权限错误有关。

Kev*_*ase 5

您正在尝试打开目录,而不是文件,因为dirname在此行调用:

passwordList = open(os.path.dirname(file+'.txt'),"r")
Run Code Online (Sandbox Code Playgroud)

要打开文件而不是包含文件的目录,您需要以下内容:

passwordList = open(file + '.txt', 'r')
Run Code Online (Sandbox Code Playgroud)

或者更好的方法是,使用该with构造来确保在处理完文件后将其关闭。

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

# passwordList has now been closed for you.
Run Code Online (Sandbox Code Playgroud)

在Linux上,尝试打开目录会IsADirectoryError在Python 3.5和IOErrorPython 3.1中引发:

IsADirectoryError:[Errno 21]是目录:'/ home / kjc /'

我没有Windows盒子可以进行测试,但是根据Daoctor的评论PermissionError当您尝试打开目录时,至少有一个Windows版本会引发。

PS:我认为您应该信任用户自己输入整个目录和文件名---而无需在其上附加'.txt'---或者您只要求目录,然后附加默认目录文件名(如os.path.join(directory, 'passwords.txt'))。

无论哪种方式,都要求先请求一个“目录”,然后将其存储在一个名为的变量中,这肯定file会造成混淆,因此请选择其中一个。