简体   繁体   English

Python Errno13权限被拒绝

[英]Python Errno13 Permission Denied

I'm getting a permission denied error when trying to use glob to get a filename list and csv to open csv files for dictionary reading. 尝试使用glob获取文件名列表和csv打开csv文件进行字典读取时,出现权限拒绝错误。 Here is my code: 这是我的代码:

import csv
import glob

#Filepath variable for the CSV files
path = "C:\\Users\\josh\\Data"

for filename in glob.glob(path):
    with open(filename) as csv_file:
        for row in csv.DictReader(csv_file):
            print row

I've tried running some file opening tests with the following code and it works perfectly. 我尝试使用以下代码运行一些文件打开测试,并且效果很好。 So I know I can open, read, write to this folder: 所以我知道我可以打开,阅读和写入此文件夹:

open('C:\\Users\\josh\\Data\\testing.txt', 'w').write('this is a test')
open('C:\\Users\\josh\\Data\\03142016.csv')

Lastly, here is the full traceback if that helps: 最后,这是完整的回溯,如果有帮助的话:

Traceback (most recent call last):

  File "<ipython-input-10-49215e5eb704>", line 1, in <module>
    runfile('C:/Users/josh/.spyder2/csvparser2.0.py', wdir='C:/Users/josh/.spyder2')

  File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 580, in runfile
    execfile(filename, namespace)

  File "C:/Users/josh/.spyder2/csvparser2.0.py", line 41, in <module>
    with open(filename) as csv_file:

IOError: [Errno 13] Permission denied: 'C:\\Users\\josh\\Data'

Any ideas? 有任何想法吗? Thank you for your help. 谢谢您的帮助。

Right now you're doing: 现在,您正在执行:

path = "C:\\Users\\josh\\Data"

for filename in glob.glob(path):

glob.glob() on only a pathname without any special globbing characters ( * , ? , etc) will just return that pathname. glob.glob() 一个路径,没有任何特殊的通配符( *? ,等)将只返回路径。 In this case the directory name, which you're not allowed to open() since that doesn't make a lot of sense. 在这种情况下,不允许使用目录名open()因为这没有多大意义。

You probably intended to write: 您可能打算写:

glob.glob(path + '\\*'):

or: 要么:

glob.glob(path + '\\*.csv'):

Bonus tip 奖金小费

You already figured out that using open('C:\\\\Users\\\\josh\\\\Data\\\\03142016.csv') works fine, which is a good first step in solving the problem. 您已经发现使用open('C:\\\\Users\\\\josh\\\\Data\\\\03142016.csv')可以很好地工作,这是解决问题的第一步。 You could have found out the error by using basic "printf-debugging": 您可以使用基本的“ printf-debugging”找出错误:

path = "C:\\Users\\josh\\Data"

for filename in glob.glob(path):
    print(filename)
    with open(filename) as csv_file:
        [.. trim ..]

This would have printed out C:\\\\Users\\\\josh\\\\Data , and not C:\\\\Users\\\\josh\\\\Data\\\\03142016.csv :-) 这将打印出C:\\\\Users\\\\josh\\\\Data ,而不是C:\\\\Users\\\\josh\\\\Data\\\\03142016.csv :-)

Lesson: when in doubt, print() out as many values as you can, and check if they're what you expect ;-) 课程:如有疑问,请尽可能多地print()值,并检查它们是否符合您的期望;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM