confusion about opening files

Arief stefanus.arief at ai.astra.co.id
Mon Sep 23 23:26:44 EDT 2002


>-----Original Message-----
>> O. K. Now I am confused.  I thought that when I imported the os
>> module, i
>> would have to call its functions like this: os.open()    Why am I just
>> using
>> the function name?
>
>Because there are two different open functions here.  One is in the
>builtins, one is in the os module.  They are not the same:
>
>>>> import os
>>>> print open.__doc__
>file(name[, mode[, buffering]]) -> file object
>
>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.
>Note:  open() is an alias for file().
>
>>>> print os.open.__doc__
>open(filename, flag [, mode=0777]) -> fd
>Open a file (for low level IO).
>
>The os.open is a low-level API and is rarely going to be the one you
>want.

The os.open is os syscall (system call). It is used to open file, fifo,
device, etc in UNIX or Linux environment (I don't know about MS Windows).
Because it is an os syscall, so any further operation should use appropriate
os syscall too, for example:

import os
fname = '/tmp/a.txt'
fd = os.open(fname)	# open file, get file descriptor used by OS
os.write(fd, 'this is only example\n')	# further operation - write file
...
os.read(fd, 1024)		# further operation - read file 1024 bytes
...
os.close(fd)	# closing file

The built in function: "open" uses c function "fopen". It is a buffered
version of os syscall "open" implementation. You should use appropriate
function for further operation too, for example:

fname = '/tmp/a.txt'
f = open(fname, 'w')
f.write('this is only example\n')
f.close()

It is "not guaranteed" that as soon as you complete the f.write call, the
file is written with data you've feed. Because it is a buffered operation.
So to assure the OS to write your text immediately, you should do this:

fname = '/tmp/a.txt'
f = open(fname, 'w')
f.write('this is only example\n')
f.flush()		# flush buffered data for previous write operation
f.close()


I hope it would help you. Any correction is welcomed ...

-----
Arief





More information about the Python-list mailing list