Forklift17
Forklift17

Reputation: 2477

Trouble appending the path directory in Python

The following script runs just fine for me:

def readData(fname):
    with open(fname, encoding="utf8") as f:
        read_data = f.read()
    return read_data

data = readData('D:/bar/foo.txt')

But when I try to run this:

from sys import path
path.append('D:/bar/')

def readData(fname):
    with open(fname, encoding="utf8") as f:
        read_data = f.read()
    return read_data

data = readData('foo.txt')

The "with" line produces this error:

FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt'

When I print sys.path, it does include the bar directory.

Why can't Python find my file? Is it necessary to specify the directory when loading it?

Upvotes: 0

Views: 57

Answers (3)

dkearn
dkearn

Reputation: 591

As Bart mentioned, sys.path tells the interpreter where it should look for modules that you attempt to use via the import statement.

sys.path doesn't have anything to do with the built in open() function (documentation).

The file argument you provide to the open() function should be an absolute path to the file, or a relative path from the working directory.

Your first example works because you have provided an absolute path to the file. Your second example (presumably) doesn't work because the script you are executing and foo.txt are not in the same directory (or if you are using the interpreter interactively, foo.txt isn't in the working directory).

Upvotes: 1

Mateusz Boruch
Mateusz Boruch

Reputation: 318

You need to set up your working directory. I.e I'm using pycharm, so I'll describe how to do it here. I just click on File --> Settings --> Build, Execution, Deployment --> Console --> Python Console.

And you set up your default working directory there For example D:\dev\Python\your project_name

Upvotes: 0

Bart Friederichs
Bart Friederichs

Reputation: 33521

sys.path is the search path for modules. Your script tries to find the file in the current working directory (probably the dir you started your script in).

You can find that with os.getcwd().

Upvotes: 0

Related Questions