# How to open a file to read and write

### Opening Files

You can open files with the open function, which has the following syntax:

open(name[, mode[, buffering]])

The open function takes a file name as its only mandatory argument, and returns a file object. The mode and buffering arguments are optional.

The following code opens a file called somefile.txt stored in the directory C:\text,

f = open(r'C:\text\somefile.txt')

If the file doesn't exist, you may see an exception traceback. If you use open with only a file name, the file is opened in read from.

If you want to write to the file, you have to state that explicitly, supplying a mode. The mode argument are summarized in the following table.

ValueDescription
'w' Write mode
'a' Append mode
'b' Binary mode (added to other mode)

The write mode enables you to write to the file.

The '+' can be added to any of the other modes to indicate that both reading and writing is allowed. So 'r+' can be used when opening a text file for reading and writing.

The 'b' mode changes the way the file is handled. rb' to read a binary file.

### turn file content to list or tuple


print list(open('script1.py'))
print tuple(open('script1.py'))
print '&&'.join(open('script1.py'))
#   www  .j  a va 2  s  . c o m
a, b, c, d = open('script1.py')

print a
print b
print c
print d


### Working with File Objects

open returns a file object, which has methods and attributes for getting information about and manipulating the opened file.


f = open("aFile.txt", "rb")
# from  ww w  .j av a  2  s . c  o m
print f

print f.mode

print f.name


### Use file pointer to get file content


f = open('somefile.txt', 'w')
print >> f, 'This is the first line'
print >> f, 'This is the second line'
print >> f, 'This is the third line'
f.close()# from   w  ww.  ja va2 s  . c  o  m

Home »
Python »