gpt4 book ai didi

读取时出现 Python 权限错误

转载 作者:可可西里 更新时间:2023-11-01 09:44:35 26 4
gpt4 key购买 nike

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 上读到的所有其他问题都是关于写入文件和获取权限错误。

最佳答案

你试图打开一个目录,而不是一个文件,因为在这一行调用了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 机器来测试它,但根据 Daoctor's comment ,至少有一个版本的 Windows 在您尝试打开目录时引发 PermissionError

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

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

关于读取时出现 Python 权限错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38711568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com