user2827580
user2827580

Reputation: 13

what directory does open() use by default?

I'm trying to do this:

for line in open('some.txt'):

and it's saying the file is not found. I have the file in the same direction as my python program. what's wrong? I thought it checked the directory to be

SOLUTION: I used os.listdir() and found out my file was actually named some.txt.txt

Upvotes: 1

Views: 142

Answers (4)

Trevor Merrifield
Trevor Merrifield

Reputation: 4701

To add to icktoofay's answer, to open a file relative to the script's folder, you could do the following.

dirname = os.path.dirname(__file__)
path = os.path.join(dirname, 'some.txt')
for line in open(path):
    ...

Upvotes: 1

icktoofay
icktoofay

Reputation: 129039

Relative paths are resolved from the current working directory.

For example, let's say I have this directory structure:

/home/joe
├── data
│   └── numbers.txt
└── programs
    └── process.py

If I were in my home directory (/home/joe), then I could reference the Python script by programs/process.py and the data file by data/numbers.txt. You could also opt to use absolute paths, e.g., /home/joe/programs/process.py and /home/joe/data/numbers.txt.

You can access the parent directory with ... For example, if I were in the programs directory and I wanted to access numbers.txt, I could use ../data/numbers.txt (or an absolute path, as before).

Your script can examine its current working directory using os.getcwd and change the current working directory using os.chdir.

The critical thing to note is that while the current working directory and directory the script is in may be the same, that is not necessarily the case. If you want to access a file in the same directory as the script regardless of what the current working directory is, you can chain a few things together:

  1. __file__ is a predefined global variable corresponding to the script's path as it was provided to the Python executable.
  2. os.path.dirname lets you get the directory from that.
  3. os.path.join lets you combine that directory and the name of the file you want to access.

Upvotes: 2

Jay
Jay

Reputation: 9582

It should be the directory you ran the python script from.

Use this to print it:

import os
print os.getcwd()

Upvotes: 0

Veedrac
Veedrac

Reputation: 60167

It uses the same directory as the current working directory. Use

import os
os.path.abspath(os.curdir)

to find out where that is.

Upvotes: 1

Related Questions