Cyberithub

Best Explanation of Python File I/O(Input/Output) with Examples

In this Python tutorial, we will look into Python File I/O(Input/Output) with Examples. If you are following up the Python Tutorial Series then in the previous tutorial, we have discussed about Error and Built-In Exceptions in Python so in this tutorial we will go ahead and discuss another important concept of Python File I/O(Input/Output).

We must first open a file to perform read from or write to operations on it. Once done we must close the file to free up the resources it holds. In python there are built in functions and modules available to perform all such file operations. We will go through them one by one. We will apply all below concepts on text files.

Best Explanation of Python File I/O(Input/Output) with Examples

Python File I/O(Input/Output) with Examples

Also Read: Error and Built-In Exceptions in Python with Best Examples

Python File Modes

r -> Opens the file in read mode. (default mode). It reads from the beginning of the file.

r+ -> Opens the file in both read and write mode. It reads from the beginning of the file.

w -> Opens the file in write mode. It overwrites the file if already exist. If file doesn't exist it created, it first then writes it.

w+ -> Opens the file in both read and write mode. It over write the file if already exist. If file doesn't exist it created; it first then writes it.

Advertisements

x -> Exclusive creation; fails if a file already exists.

a -> Opens the file in write mode. If file exists, it writes from the end of file. If file doesn't exist, it creates it and then write it.

a+ -> Opens the file in both read and write mode. If file exists, it starts writing from the end of file. If file doesn't exist, it creates it and then write it.

t -> Opens a file in text mode (default)

b -> Opens a file in Binary mode. More on Python File Input and Output Official Documentation.

Open File In Python

To open a file in python, we use open() built in function. There is no need to import any module to use this function.

Syntax

open("FileName", "Mode", "Encoding")

File must reside in present working directory to open. Else provide full path to switch to the directory where file is present. In below example, we open a file in read mode and also pass the encoding mode.

We are using below Recipe.txt file in all the below examples.

Recipe.txt:-
Receipe
Boil Water
Add Ingredients
Cook For 10 Mins
Ready To Eat !!

Program Example

import os
import touch

os.getcwd()
os.chdir(r"C:\Users\adam\Desktop")

file = open("Recipe.txt", "r", encoding='utf-8')
for line in file:
print(line, end="")

Output

C:\Users\adam\PycharmProjects\Demo\venv\Scripts\python.exe C:/Users/adam/PycharmProjects/Demo/File_io.py
Recipe
Boil Water
Add Ingredients
Cook For 10 Mins
Ready To Eat !!

Close File In Python

To close a file in python, We use built in function called close(). There is no need to import any module to use this function.

Syntax

fileObject.close()

Program Example

import os
import touch

os.getcwd()
os.chdir(r"C:\Users\adam\Desktop")

file = open("Recipe.txt", "r", encoding='utf-8')
for line in file:
print(line, end="")
file.close()

Output

C:\Users\adam\PycharmProjects\Demo\venv\Scripts\python.exe C:/Users/adam/PycharmProjects/Demo/File_io.py 
Recipe 
Boil Water 
Add Ingredients 
Cook For 10 Mins 
Ready To Eat !!

'with' In Python

When we work with large number of files in python, we may forget to close few files which will cause error if some other object tries to operate on same file. We can use 'with' in such cases which will implicitly close the files once it completes the execution of statements within its block.

Program Example

import os
import touch

os.getcwd()
os.chdir(r"C:\Users\adam\Desktop")
with open("Recipe.txt", "r", encoding='utf-8') as file:
for line in file:
print(line, end="")

Output

C:\Users\adam\PycharmProjects\Demo\venv\Scripts\python.exe C:/Users/adam/PycharmProjects/Demo/File_io.py
Recipe
Boil Water
Add Ingredients
Cook For 10 Mins
Ready To Eat !!
       
Process finished with exit code 0

Read File In Python

In python, we can read a file using multiple methods. They are defined below.

1. read() -> read() method takes number of character to be read as parameter. By default if no argument is passed, it will read up to the EOF . In below example, first print statement will read 7 character, second will read 6 character and last print will then read till EOF.

Program Example

import os
import touch

os.getcwd()
os.chdir(r"C:\Users\adam\Desktop")
with open("Recipe.txt", "r", encoding='utf-8') as file:
print(file.read(7))
print(file.read(6), "\n")
print(file.read())

Output

C:\Users\adam\PycharmProjects\Demo\venv\Scripts\python.exe C:/Users/adam/PycharmProjects/Demo/File_io.py
Recipe
Boil
Water
Add Ingredients
Cook For 10 Mins
Ready To Eat !!
Process finished with exit code 0

2. seek()/tell() -> tell() method in python tells the current position of the cursor. seek() method in python set cursor at the specified position which we pass as an argument to it. In below example, we read first 7 character then tell() shows the cursor position at 7. seek() method reset the cursor position at character 20. read() will start reading from this character onward till EOF.

Program Example

import os
import touch

os.getcwd()
os.chdir(r"C:\Users\adam\Desktop")
with open("Recipe.txt", "r", encoding='utf-8') as file:
print(file.read(7))
print(file.tell())
print(file.seek(20))
print(file.read())

Output

C:\Users\adam\PycharmProjects\Demo\venv\Scripts\python.exe C:/Users/adam/PycharmProjects/Demo/File_io.py
Recipe
7
20
Add Ingredients
Cook For 10 Mins
Ready To Eat !!
Process finished with exit code 0

3. readline() -> readline() method in python reads the file until it find the new line character. Hence, it reads individual lines including new line character. In below example, first print statement will print 'Recipe' as it finds new line character after it. Second print statement will print Boil Water as it finds new line character after it.

Program Example

import os
import touch

os.getcwd()
os.chdir(r"C:\Users\adam\Desktop")
with open("Recipe.txt", "r", encoding='utf-8') as file:
print(file.readline())
print(file.readline())

Output

C:\Users\adam\PycharmProjects\Demo\venv\Scripts\python.exe C:/Users/adam/PycharmProjects/Demo/File_io.py
Recipe
Boil Water
Process finished with exit code 0

4. readlines() -> readlines() method in python reads rest of the lines in a file and returns in a list. In below example, first print statement will return first line and second print statement will return rest of the lines in form of list.

Program Example

import os
import touch

os.getcwd()
os.chdir(r"C:\Users\adam\Desktop")
with open("Recipe.txt", "r", encoding='utf-8') as file:
print(file.readline())
print(file.readlines())

Output

C:\Users\adam\PycharmProjects\Demo\venv\Scripts\python.exe C:/Users/adam/PycharmProjects/Demo/File_io.py
Recipe
['Boil Water\n', 'Add Ingredients\n', 'Cook For 10 Mins\n', 'Ready To Eat !!\n', '        ']
Process finished with exit code 0

Write File In Python

In Python to write in a file, we must first open it either in 'w' or 'a' mode. If open in 'w' mode, it will over write the existing file and all previous data will be lost. If open in 'a' mode, it will append the end of file. To perform the write operation on files, write() and writelines() methods are used.

Program Example

list1 = ["This\n", "is\n", "first\n", "file\n"]

with open("Test.txt", 'w', encoding='utf-8') as file:
file.write("Hello !!\n")
file.writelines(list1)
with open("Test.txt", 'r', encoding='utf-8') as file:
print(file.read())

Output

C:\Users\adam\PycharmProjects\Demo\venv\Scripts\python.exe C:/Users/adam/PycharmProjects/Demo/File_io.py
Hello !!
This
is
first
file
Advertisements

Leave a Comment