Python 读取时权限错误

Python Permission Error when reading

import os
import rarfile

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

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

使用此代码我收到错误:

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'

这很奇怪,因为我拥有此文件的完全权限,因为我可以编辑它并做任何我想做的事,而我只是想阅读它。我在 Whosebug 上读到的所有其他问题都是关于写入文件和获取权限错误的。

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

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

要打开文件而不是包含它的目录,您需要这样的东西:

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

或者更好的是,使用 with 构造来保证文件在您完成处理后关闭。

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

# passwordList has now been closed for you.

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

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

我没有 Windows 框来测试它,但根据 ,至少有一个版本的 Windows 会引发 PermissionError 当你尝试打开一个目录。

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

无论哪种方式,请求 "directory" 然后将其存储在名为 file 的变量中肯定会造成混淆,因此请选择一个。

os.path.dirname() 将 return 文件所在的目录而不是文件路径。例如,如果 file.txt 在 path= 'C:/Users/Desktop/file.txt' 中,那么 os.path.dirname(path)wil return 'C:/Users/Desktop' 作为输出,而 open() 函数需要一个文件路径. 您可以将当前工作目录更改为文件位置并直接打开文件。

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

open(os.path.join(<fileDirectory>,<fileName>),'r')