On 18.03.2011 22:33, Jon Herman wrote:
Hello all,

I am pretty new to Python and am trying to write data to a file. However, I
seem to be misunderstanding how to do so. For starters, I'm not even sure
where Python is looking for these files or storing them. The directories I
have added to my PYTHONPATH variable (where I import modules from
succesfully) does not appear to be it.

So my question is: How do I tell Python where to look for opening files, and
where to store new files?

Thanks,

Jon




There is no special place where Python looks for normal files (PYTHONPATH is just tells where to look for modules.)

If you open a file (for reading and/or writing) and don't give an absolute path, then the filename is relative to the CWD (Current Working Directory). One can change this directory with os.chdir() *but* you shouldn't need to do that. Either start Python in the desired directory (your operating system will have a way to do this for icons and menu entries) or give an absolute path like:

f = open("/home/alex/test.txt")
f = open("c:/test.txt")

Also check out os.environ, a dict containing the environment variables. There you will find variables like $HOME or %USERPROFILE% (if that's correct) which tells where your personal files are:

import os

# my home directory is /home/alex
homedir = os.environ["HOME"]

# creates the file /home/alex/test.txt
f = open(os.path.join(homedir, "test.txt"))
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to