Signup/Sign In

File Handling in Python

Not in every case data is supposed to be taken directly from the user. There may arise cases when you have to take data from a stored raw file, in such cases, you will have to connect those files with a program such that it can read, write or modify the data.

In this section, we will see how to perform these tasks.


File Access Modes

Since there is various purpose of using a file along with Python (i.e., read, write, append), it is important to specify each time for what operations Python should expect on the file. Thus, there are various access modes which we have to specify while opening a file in a program.

Python is capable of managing two type of files - Text(or normal characters) and Binary(Text only containing 1 and 0). Along with the access mode, it is also necessary to specify which type of file it is going to open.


Python - Opening a File

In order to connect our program with the desired file, we need a stream that can fetch or write data in it. For this purpose, there are already some in-built classes/functions which we can utilize to solve the purpose. The first thing that we need to do is create a file object, i.e., Instance of File class which we can do using file() or open() function. In order to open a file -

>>> myFile = open([path of file], [access mode], [buffer size])

Here myFile will be the object of the file and open() method will open the file specified in the [path of file]. Other two arguments, [access mode] will provide the access mode and [buffer size] will ask for how many chunks of data is to be retrieved from the file. Although, last two parameters [access mode] and [buffer size] are completely optional. By default, if there is no access mode specified then it is considered to be reading mode. [path of file] can be the complete path of the file or if it exists in the same file as a program then only providing the name is sufficient. More clearly-

Opening a file python

In above case, writing

>>> myFile = open("file.txt")

is sufficient. However, in situations like-

Opening a file in python

Note that this time your file.txt is not in the same folder as in above case, thus here you will have to specify the whole location.

>>> myFile = open("C:/c_code/file.txt")

Once the file had been opened there is something called pointer that points to some position in the file. This pointer is used to read/write from that position. This pointer is pretty much like a text cursor which can be shifted freely (using arrow keys) or used to write or delete the text from a text, except that pointer can shift/read/write only through some functions.

About access modes now, following are the available access modes that are to be specified in the argument-

  1. read mode - "r" for text files and "rb" for binary files. File pointer points at the beginning of the file.
    >>> myFile = open("file.txt", "r")
  2. write mode - "w" for text files and "wb" for binary files. File pointer points at the beginning of the file.
    >>> myFile = open("file.txt", "w")
  3. append mode - "a" for text files and "ab" for binary files. File pointer points at the end of the file.
    >>> myFile = open("file.txt", "a")
  4. read/write mode - "r+" or "w+" provide the option for doing both read and write operation on the same file object. "rb+" or "wb+" for binary files. File pointer points at the beginning of the file.
    >>> myFile = open("file.txt", "r+")
  5. append/read - "a+" to enable read/append mode, "ab+" for append/read mode on binary files. File pointer points at the end of the file.
    >>> myFile = open("file.txt", "a+")

As you can see opening files this way is pretty much similar to creating an object a file and doing some operations with/on it for read/write. Opening files in this way create a stream of the data buffer, after using the file it is always recommended to close this stream. This can be done using the close function. For instance, to close the myFile stream

>>> myFile.close()

Another way of using a file is using with keyword. Looking at syntax will make it clear how this works-

with open("file.txt", "r+"):
		// operations to perform on "file.txt"
		// there can be many
		// syntax is pretty much like that of methods

With this way, you are actually creating a scope for the file to be used. Once the program gets out of this scope the file gets closed itself.

More about reading and writing data into a file in next section.