Reading/Writing files
Westley MartÃnez
anikom15 at gmail.com
Fri Mar 18 18:27:45 EDT 2011
On Fri, 2011-03-18 at 15:56 -0600, Jon Herman wrote:
> Jack,
>
> thanks.
>
> Alright, so what I did is create a file called hello.txt with a single
> line of text in there. I then did the following:
>
> f="fulldirectory\hello.txt" (where fulldirectory is of course the
> actual full directory on my computer)
> open("f", "w")
>
> And I get the following error: IOError: [Errno 13] Permission denied:
> 'f'
> If I open to read, I get: IOError: [Errno 2] No such file or
> directory: 'f'
>
> Can anyone explain to me why this happens?
>
>
>
>
> On Fri, Mar 18, 2011 at 3:50 PM, Jack Trades
> <jacktradespublic at gmail.com> wrote:
>
>
> On Fri, Mar 18, 2011 at 4:33 PM, Jon Herman
> <jfc.herman at gmail.com> 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
>
>
>
> By default Python will read and write files from the directory
> that your program is run from. This cannot always be relied
> upon though (for instance if your program was imported as a
> module from another program).
>
> To find out what directory your program is currently in use
> os.getcwd(). Here's an example I just ran...
>
> >>> import os
> >>> os.getcwd()
> '/media/DATA/code/lispy/liSpy'
>
> The folder that is returned from os.getcwd() is the folder
> that "open" will use. You can specify another folder by
> giving the full path.
>
> open("/full/path/to/file.txt", "w")
>
> PYTHONPATH is for importing modules, which is a separate
> concern.
>
> --
> Jack Trades
> Pointless Programming Blog
>
>
Don't put f in quotes. That would just make the string literal 'f'.
More information about the Python-list
mailing list