[Tutor] file(), open()

Rikard Bosnjakovic rikard.bosnjakovic at gmail.com
Sat May 26 15:00:58 CEST 2007


On 5/26/07, Alan Gilfoy <agilfoy at frontiernet.net> wrote:
> How do you refer to the filename? Do you put it in quotes?

Yes.  open("foo")

> Do you put
> in the file's full directory path? Or do file() and open() refer to
> the same directory as the one the script is in?

Yes, and yes. If you dont supply the absolute path, the script will
read the file from the cwd (current working dir). This is _usually_
the same as the script, but not necessarily. If the cwd is /foo/bar
and the script is launched using /bar/foo/foo/foo/script.py, then
open("file") will refer too /foo/bar/file, while
open("/bar/foo/foo/foo/file") will get the file from the same dir as
the script itself.

This is handled by the OS.

> Are the mode and buffering things always necessary arguments?

Both mode and buffering are optional. I have during my 7 years of
Python-coding never used the buffering-flag.

> What do file() and open() create? Do you need to set them equal to
> some variable? Is one better than the other?

open() and file() are the same functions. Try "print open.__doc__" in
your Python interpreter, and you will see this:

Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending.  The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing.  Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.


> I want to create a list, where each list item is a line in the file.
> (The, my program would do stuff with the list.)

mylist = open("listfile").readlines()


-- 
- Rikard - http://bos.hack.org/cv/


More information about the Tutor mailing list