Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does Python first look for files?

Tags:

python

file

I'm trying to learn how to parse .txt files in Python. This has led me to opening the interpreter (terminal > python) and playing around. However, I can't seem to be able to specify the right path. Where does Python first look?

This is my first step:

    f = open("/Desktop/temp/myfile.txt","file1")

This blatantly doesn't work. Can anyone advise?

like image 466
Federer Avatar asked Nov 03 '09 16:11

Federer


2 Answers

That doesn't work as you've got the wrong syntax for open.

At the interpreter prompt try this:

>>> help(open)
Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.

So the second argument is the open mode. A quick check of the documentation and we try this instead:

f = open("/Desktop/temp/myfile.txt","r")
like image 68
Dave Webb Avatar answered Sep 22 '22 06:09

Dave Webb


Edit: Oh and yes, your second argument is wrong. Didn't even notice that :)

Python looks where you tell it to for file opening. If you open up the interpreter in /home/malcmcmul then that will be the active directory.

If you specify a path, that's where it looks. Are you sure /Desktop/temp is a valid path? I don't know of many setups where /Desktop is a root folder like that.

Some examples:

  • If I have a file: /home/bartek/file1.txt

  • And I type python to get my interpreter within the directory /home/bartek/

  • This will work and fetch file1.txt ok: f = open("file1.txt", "r")

  • This will not work: f = open("some_other_file.txt", "r") as that file is in another directory of some sort.

  • This will work as long as I specify the correct path: f = open("/home/media/a_real_file.txt", "r")

like image 39
Bartek Avatar answered Sep 25 '22 06:09

Bartek