Programming Essentials in Python for a Data Scientist
By: S. Khan
Tags: Python3, Tutorial, Programming, Python, Data Science

Files

File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.

>>> f = open("test.txt") # open file in current directory

>>> f = open("C:/Python38/README.txt") # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file. We can also specify if we want to open the file in text mode or binary mode.

The default is reading in text mode. In this mode, we get strings when reading from the file.

On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like images or executable files.

f = open("test.txt") # equivalent to 'r' or 'rt' - t: text mode

f = open("test.txt",'w') # write in text mode

f = open("img.bmp",'r+b') # read and write in binary mode

When working with files in text mode, it is highly recommended to specify the encoding type i.e utf-8 here. By default in windows, it is cp1252 but utf-8 in Linux.

>>> f = open("test.txt", mode='r', encoding='utf-8')

Closing the File

When we are done with performing operations on the file, we need to properly close the file.

Closing a file will free up the resources that were tied with the file. It is done using the close() method available in Python.

>>> f = open("test.txt", encoding = 'utf-8')

>>> # perform file operations

>>> f.close()

This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.

A safer way is to use a try…finally (exception handling) block.

>>> try:

>>> f = open("test.txt", encoding = 'utf-8')

>>> # perform file operations

>>> finally:

>>> f.close()

This way, we are guaranteeing that the file is properly closed even if an exception is raised that causes program flow to stop.

Create a New File

In order to write into a file in Python, we need to open it in write w , append a or exclusive creation x mode.

We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.

Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

>>> f = open("test.txt", "a")

>>> f.write("my first file

")

>>> f.write("This file



")

>>> f.write("contains three lines

")

>>> f.close()

The above example opens the file “test.txt” and append content to the file.

Read Only Parts of the File

To read a file in Python, we must open the file in reading r mode.

We can read the text.txt file we wrote in the above section in the following way:

>>> f = open("test.txt",'r',encoding = 'utf-8')

>>> f.read(4) # read the first 4 data

'This' >>> f.read(4) # read the next 4 data

' is ' >>> f.read() # read in the rest till end of file

'my first file

This file

contains three lines

' >>> f.read() # further reading returns empty sting

''

Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

>>> import os

>>> os.remove(“ test .txt”)

To avoid getting an error, you might want to check if the file exists before you try to delete it: