Reading/Writing files

Dan Stromberg drsalists at gmail.com
Fri Mar 18 18:18:57 EDT 2011


Are you on windows?

You probably should use / as your directory separator in Python, not \.  In
Python, and most other programming languages, \ starts an escape sequence,
so to introduce a literal \, you either need to prefix your string with r
(r"\foo\bar") or double your backslashes ("\\foo\\bar").

/ works fine on windows, and doesn't require escaping ("/foo/bar").

On Fri, Mar 18, 2011 at 2:56 PM, Jon Herman <jfc.herman at gmail.com> 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 <http://pointlessprogramming.wordpress.com>
>>
>>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110318/0bc2d4d6/attachment-0001.html>


More information about the Python-list mailing list