Re: open() and file CREATION

Tim Peters (tim@ksr.com)
Fri, 11 Feb 94 14:52:43 EST

> I must be going crazy or loosing my mind..

Some people have all the luck <wink>.

> How do I CREATE a file from Python? I normally just OPEN an already
> existing file.. Now I need to CREATE one.. open() will not do it..

Well, the builtin open() works for me:

>>> os.stat('glort') # showing that file 'glort' doesn't exist now
Traceback (innermost last):
File "<stdin>", line 1
posix.error: (2, 'No such file or directory')
>>> f = open('glort','w') # open glort for writing
>>> os.stat('glort') # showing that it exists now
(33204, 23229, 2638, 1, 82, 120, 0, 760995223, 760995223, 760995223)
>>> f.write('abcdefg\n') # write something to it
>>> f.close() # close it
>>> f = open('glort','r') # open it for reading
>>> f.readlines() # no surprise here
['abcdefg\012']
>>>

Opening for append (passing the 'a' flag to open()) also creates a file;
opening for read ('r' flag) won't create a non-existent file, and I
wouldn't expect it to.

Maybe you're suffering a porting problem? I tried these under SunOS and
KSR's OS (an OSF/1 variant).

> Also, why are there no flags defined in the posix module? [O_RDONLY etc]

I haven't messed with this level of control from Python, but note that
the distribution contains files FCNTL.py under the Lib/sgi/ and Lib/sun4/
subdirectories. Symbols O_RDONLY etc are defined there.

suspecting-that-will-get-you-most-of-the-way-there-ly y'rs - tim

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp