阅读时出现Python权限错误

阅读时出现Python权限错误

本文介绍了阅读时出现Python权限错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'

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

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.

推荐答案

由于要调用 dirname ,因此您试图打开一个目录,而不是一个文件.在这一行:

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')

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

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.

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

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

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

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:我认为您应该信任用户自己输入自己的整个目录和文件名,而不必在其上附加'.txt'否则,您只需要询问目录,然后向其附加一个默认文件名即可(例如 os.path.join(directory,'passwords.txt')).

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')).

无论哪种方式,都要求先找到一个目录",然后将其存储在一个名为 file 的变量中,以免造成混淆,因此请选择其中一个.

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.

这篇关于阅读时出现Python权限错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:34