3

Every example I see about opening a file in Python has something like this:

myFile = open('somefilenamehere', 'r') 

It never works for me when I just type the file name...you should always put full directory path where that file is

myFile = open('C:\\blah\\blah\\somefilenamehere', 'r') 

Does it work for someone? I mean just putting the name of the file?

5
  • 3
    Yes. Python scripts have a current working directory. If the file you're trying to open is in the current working directory, then it'll work, if not, you need to give the path to it (be it relative or absolute). You can also change your current working directory using the os module. Commented Mar 25, 2015 at 13:23
  • If your Python file (*.py) and the file to be opened are in same directory, it will work. Commented Mar 25, 2015 at 13:23
  • @PrerakSola that's not precise. The process working directory is not always (and very often is not) the same as the script file directory. Commented Mar 25, 2015 at 13:32
  • It's obviously not working, but since our paths differ, there is no point to even try to give paths. Commented Mar 25, 2015 at 13:34
  • As a side-note, if you need to specify Windows paths in your scripts, I suggest you to use raw strings to specify pathnames, e.g. myFile = open(r'C:\blah\blah\somefilenamehere', 'r'). Commented Mar 25, 2015 at 17:20

2 Answers 2

4

That has more to do with the process working directory than with where the script is. For example, you have a script called cat.py like:

import sys with open(sys.argv[1]) as fp: print fp.read() 

and then you do:

$ cd /tmp $ echo 12345 > test.txt $ python /path/to/cat.py test.txt 12345 

This will work as expected regardless of the script location, since the working directory is /tmp and the script doesn't change it.

Sign up to request clarification or add additional context in comments.

Comments

-1

It's a relative path. So, you can put only filename if you run script in the same directory.

1 Comment

What happens if I change my working directory in the script with os.chdir?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.