Search code examples
pythonpathioerror

IOError: [Errno 13] when specifying path for functions


I am making a search engine and I need some help clearing the code where I choose a folder for searching.

I make the user specify a path with this function:

def location_specify():
    location = raw_input('Define path for search: ')
    return location

location = location_specify()

This location I use for the following function where I want to open the documents in the folder and tokenize.

def open_doc(location):
    docfile = codecs.open(location, 'r', encoding='utf-8')
    doclist = docfile.read().lower().split()
    docfile.close()
    return doclist

I tested this function with this path:

C:\\Users\\Vestergaard\\Desktop\\Informationssoegning\\Ernaeringskorpus

and I receive this errormessage

Traceback (most recent call last):
    File "<pyshell#16>", line 1, in <module>
    open_doc(location)
    File "<pyshell#15>", line 2, in open_doc
    docfile = codecs.open(location, 'r', encoding='utf-8')
    File "C:\Python27\lib\codecs.py", line 884, in open
    file = __builtin__.open(filename, mode, buffering)
    IOError: [Errno 13] Permission denied: 'C:\\Users\\Vestergaard\\Desktop\\Informationssoegning\\Ernaeringskorpus'

I don't know what I'm doing wrong. Maybe my functions are way off?


Solution

  • import codecs, os
    
    def open_doc(directory):
        allfiles = {}
        for filename in os.listdir(directory):
            docfile = codecs.open(os.path.join(directory, filename), 'r', encoding='utf-8')
            content = docfile.read().lower().split()
            docfile.close()
            allfiles[filename] = content
        return allfiles