读取时出现Python权限错误

2024-09-27 09:32:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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'

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


Tags: 文件pathimporttxtinputos错误open
2条回答

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

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

或者

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

您正试图打开一个目录,而不是一个文件,因为在此行中调用了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上,尝试打开目录会在Python3.5中引发一个IsADirectoryError,在Python3.1中引发一个IOError

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

我没有Windows框来测试这个,但是根据Daoctor's comment,当您试图打开目录时,至少有一个版本的Windows会引发PermissionError

注:我认为您应该信任用户输入整个目录并命名他或她自己,而不需要在其中附加'.txt'文件名,或者您应该只请求目录,然后在其中附加一个默认文件名(如os.path.join(directory, 'passwords.txt'))。

不管怎样,请求一个“目录”,然后将其存储在一个名为file的变量中肯定会让人感到困惑,所以选择其中一个。

相关问题 更多 >

    热门问题