Reading/Writing files

Ethan Furman ethan at stoneleaf.us
Fri Mar 18 18:01:38 EDT 2011


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?

There's nothing magical about it (plenty of irritating and frustrating 
if using Windows, though ;).

somefile = open('test.txt') # opens file test.txt in current directory
someotherfile = open('./stuff/misc.txt') # opens misc.txt, which lives
                                          # in stuff which lives in the
                                          # the current directory
thatfile = open(r'c:\blah\whodunit.clu') # opens whodunit.clu which
                                          # lives in blah off the C:
                                          # drive

To get the current directory, if you don't know what it is:

import os
os.getcwd()

and if you want to change the current directory:

os.chdir('/some/new/path')

~Ethan~



More information about the Python-list mailing list