>>> f=open('p.txt','w') # open for writing
>>> dir(f)
['close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name', 'read',
'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell',
'truncate', 'write', 'writelines', 'xreadlines']
>>> f.write('first line\n')
>>> f.write('second line\n')
>>> f.close() # close file
>>> f=open('p.txt','r') # open for reading
>>> for line in f.readlines():
... print line
...
first line
second line
>>> f.close() # close file
>>> f=open('p.txt','a') # open appending
>>> f.write('new line with a number ' + str(12.25)+'\n')
>>> f.close()
>>> f=open('p.txt','r') # open for reading
>>> for line in f.readlines():
... print line
...
first line
second line
new line with a number 12.25
Di solito, specialmente per i file, è utile sapere se il file che stiamo
tentando di aprire esiste, al fine di non proseguire in caso di errore.
A tale scopo usiamo il costrutto try: except:, come nel caso
>>> f=open('p1.txt','r') # open for reading
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'p1.txt'
>>> def test_open_file(filename,mode): # define a test function
... try:
... f=open(filename,mode)
... except:
... f=None
... print 'Error in file ',filename,'with mode',mode
... return f
...
>>> f=test_open_file('p.txt','r')
>>> f
<open file 'p.txt', mode 'r' at 0x810f138>
>>> f.close()
>>> f=test_open_file('p1.txt','r')
Error in file p1.txt with mode r
>>> f
>>>
Per un più approfondito utilizzo dei file si rimanda a www.python.org/doc/.