Python Files I/O

In this article, you will learn about Python files I/O from opening a file to reading it, writing it, closing it and various other file operations.

Files: Introduction
Opening a Python file
Closing a Python file
Reading and writing files in Python
Rename a file in Python
Current position in the file
Python file methods
 python files

Python Files


A file simply is a collection of data stored in the form of a sequence of bytes in a machine.

It’s a collection of data or information stored in the memory heap that has a name called filename.

There are two types of files in Python.

  1. Text Files
  2. Binary Files

Text files in Python

Text files are humanly readable which is displayed in a sequence of characters that can be easily interpreted by humans as it presented in the textual form. Common editors like notepad and others can be used to interpret and edit them.

They can be stored in plain text (.txt) format or rich text format (.rtf).

Binary files in Python

In binary files data is displayed in some encoded format (using 0’s and 1’s) instead of plain characters. Typically they contain the sequence of bytes.

They are stored in .bin format.

Any file operation can be broken down into three major steps:

  1. Opening a file
  2. Perform different file operations (Read/Write)
  3. Closing a file
 python file operaton

Opening a Python file


The open( ) method

Python has a built-in function open() to open a file. This function creates a file object.

Here is the syntax.

f = open(file_name, access_mode)

Where,

  • file_name = name of the file to be opened
  • access_mode = mode in which the file is to be opened. It can be read, write etc. By default, it opens the file in reading mode (r) if not specified explicitly. Here is the list of different modes in which a file can be opened.
    Mode Description
    r Opens a file for reading mode only.
    w Opens a file for writing mode only. Creates a new file for writing it the file doesn’t exist.
    rb Opens a binary file for reading mode only.
    wb Opens a binary file for writing mode only. Creates a new file for writing it the file doesn’t exist.
    r+ Opens a file for reading and writing mode.
    rb+ Opens a binary file for reading and writing mode.
    w+ Opens a file for writing and reading mode. Creates a new file for writing it the file doesn’t exist.
    wb+ Opens a binary file for writing and reading mode. Creates a new file for writing it the file doesn’t exist.
    a Opens a file for appending. Creates a new file for writing it the file doesn’t exist.
    a+ Opens a file for appending and reading. Creates a new file for reading and writing it the file doesn’t exist.
    ab Opens a binary file for appending. Creates a new file for writing it the file doesn’t exist.
    ab+ Opens a binary file for reading and writing mode. Creates a new file for reading and writing it the file doesn’t exist.

Example

Let’s create a text file example.txt and save it in our working directory.

python example text file

Now here is the code to open the file.

f = open('example.txt','r') #open file from working directory in reading mode
fp = open('C:/xyz.txt','r') #open file from any directory

In above example, f is a pointer variable pointing to the file example.txt.

[adsense1]

To print the content of and details of example.txt, here is the code.

>>> print (*f) #print the content of file
This is a text file.
>>> print (f) #ptint mode and encoding
<_io.TextIOWrapper name='example.txt' mode='r' encoding='cp1252'>

Note that the default encoding in Windows is cp1252 whereas in Linux default encoding is utf-08.

Closing a File in Python


The close( ) method

When we open a file in Python, it must be closed once we finish all the operations because we don’t know when data is flushed. Hence, to free up tied up resources and clean up garbages we must close the file after finishing the operations.

Python automatically closes a file once the object is assigned to another file.

Here is how the file closed in Python.

Method 1

One method is to just open up files and simply close it using close( ) method.

f = open('example.txt','r')
#file operations
f.close()

So after we close the file, we cannot use the file until we open it again.

Method 2

Another method is to use try/finally which ensures that after opening the file if file operations raise an exception, the file will be closed properly.

What happens while closing file directly is that of the operations raise an exception, the program will terminate without properly closing the file.

Here is how it is done.

f = open('example.txt','r')
try:
   #file operations
finally:
   f.close()

Note: The file must be opened before try statement because if open statement itself raises an error, the file won’t be opened to close it.

This method will ensure that, if the file operations somehow raise an error, the file will be closed before the program is terminated.

Method 3

The with statement

Another method is by using with statement, which simplifies exception handling by encapsulating both initial operations and closing or clean up tasks.

We don’t need close statement because with statement will automatically close the file.

Here is the implementation of with statement.

with open('example.txt') as f:
    #file operations

Reading and writing files in Python


In Python, we can read the files and write to files by opening up the file in corresponding modes.

The read( ) function

The read( ) function is used to read the content of a file after the file is opened in reading mode ( mode = r).

Syntax

file.read(size)

Where,

  • file = file object
  • size = number of characters we want to read. If size is not specified, it will read entire content.

Example

>>> f = open('example.txt','r')
>>> f.read(7) #reading 7 characters from example.txt
'This is '

Now the interpreter has read 7 characters of the file and if we again use read( ) function,  it will start reading from 8th character.

>>> f.read(7) #reading next 7 characters
' a text'

The readline( ) function

The readline( ) function is used to read the content line by line. It is useful for the large files and we can get access to any line at any moment.

Example

Let’s create a file test.txt containing multiple lines as:

This is line1.
This is line2.
This is line3.

Now let’s see how readline( ) function is used in test.txt.

>>> x = open('test.txt','r')
>>> x.readline()  #to display first line
This is line1.
>>> x.readline(2)  #to read second line
This is line2.
>>> x.readlines()  #to read all lines
['This is line1.','This is line2.','This is line3.']

Notice that the each line is separated even while reading all lines.

The write( ) function

The write( ) function is used to write into files in Python opened in writing mode.

Opening a file in writing mode will create a new file if the file we attempt to open doesn’t exist.

Syntax

file.write(string)

Example

Let’s assume we don’t have file xyz.txt. Hence it will be created while we open the file in writing mode.

>>> f = open('xyz.txt','w') #opening in writing mode
>>> f.write('Hello \n World')  #writing Hello World to the file
Hello
World
>>> f.close()  #closing the file

Renaming files in Python


The rename( ) function

The function rename( ) is used to rename a file in Python. For this we need to import os module first.

Here is the syntax.

import os
os.rename(src,dest)

Where,

  • src = file to be renamed
  • dest = new name for the file src

Example

>>> import os
>>> #renaming xyz.txt to abc.txt
>>> os.rename("xyz.txt","abc.txt")

Current position in Python files


In Python, it is possible to know current position in a file using a function called tell( ). Similarly, we can change the current position by using the function seek( ).

Example

>>> f = open('example.txt') #example.txt we created earlier
>>> f.read(4) #let's get to the 4th position first
This
>>> f.tell() #returns the current position
4
>>> f.seek(0,0) #repositioning the position to 0 again

This is how we can get the current position in the file and shift the position as well.

Python File Methods

Here is the tabular presentation of Python file methods.

Python file methods with description
file.close( )
Closes a file opened.
file.fileno( )
Returns an integer descriptor of a file.
file.flush( )
Flushes the internal buffer.
file.isatty( )
Returns true if the file is connected to a tty(-like) device.
file.next( )
Returns the next line in the file.
file.read(n )
Reads the first n characters of the file.
file.readline( )
Reads a single line in a string or file.
file.readlines( )
Reads and returns the list of all the lines in the file.
file.seek(offset[,whence] )
Sets the file’s current position.
file.seekable( )
Checks if file supports random access. Return true if yes.
file.tell( )
Return’s the current position in the file.
file.truncate(n )
Truncates the file’s size. If n is provided, the file is truncated to n bytes else truncated to current location.
file.write(str)
Writes the string str in the file.
file.writelines(sequence )
Write sequence of strings to the file.