Python File opening

File handling is an important concept in any programming language. Python also has functions for creating, reading, writing, updating and deleting a file. 

File handling is performed through open() method. This method takes two arguments one is file mode which is compulsory and another one is file mode to open.


Syntax:

open(filename, [mode=r])

Filename is the path of the file which we want to open. The mode defines what we want to do, are we opening a file, creating a file, updating a file, etc.

The modes are defines by letters which are listed below.

Character /file mode lettersMeaning 
‘r’open for reading(default)
‘w’open for writing, truncating (shortening) the file first
‘x’open for exclusive creating, failing if the file already exists
‘a’open for writing, appending to the end of the file if it exists
‘b’binary mode( used for images)
‘t’text mode (default )
‘+’open for updating(reading and writing)

The default mode for a file if not provided is ‘r’ or ‘rt’ meaning for reading in text mode. Modes can be combined with other items to mean various things like

w+ means opening for writing and reading in text mode.

r+ means opening for reading and writing in text mode (similar to w+).

w+b means opening for reading and writing in binary mode and so on.

Opening a file

The open() methods returns a file object. We can open a file in following ways

f = open('filename.txt')

The above code is same as 

f = open('filename.txt', 'rt')

We can also open by giving other modes. Modes are optional in open() method but if you want to open a file other than reading you need to provide mode. Lets see an example

f = open('filename.txt', 'w+')

Leave a Reply

Your email address will not be published. Required fields are marked *