• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

File Handling in Python with example

  • January 7, 2023
  • CODE OF GEEKS
  • 0
In this Tutorial -:
  • Opening a file with open() function in Python
    • Syntax of open() function
  • File Opening modes in Python
  • Reading from a file in Python
  • Closing a file in Python
  • Writing an existing file in Python
  • Creating a new file in Python
  • Checking if file exists in Python or not
  • seek() and tell() function in Python
File Handling in Python with example
File Handling in Python with example


NEXT TUTORIAL >> with statement in Python

Python File Handling is a utility that allow us to play around with file using our cool python code.

Python provides ‘n’ number of functions to perform basic operations on a particular file. These operations may be like opening a file, reading a file, writing a file, closing a file or even deleting a file.

Opening a file with open() function in Python

open() function in python is used to open a file. This file may be a text file or even a binary file.

Syntax of open() function

file = open('filename', 'open_mode', 'buffer')

open() function make use of three parameters :

  1. filename: represents the name of a file to be opened.
  2. open_mode: represents the purpose of opening a file
  3. buffer: represents a temporary block of memory. It denotes an integer value used to set the buffer size for a file(in bytes).

File Opening modes in Python

File opening modes in Python
File opening modes in Python


Above table is specified for text files only.

In case of binary files, we just need to append ‘b’ in the end of modes. Like,

wb, rb, ab, w+b, r+b, a+b are the modes for binary files.

Program: To open a file in read mode

fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
print(fp) # printing the file pointer
f.close() # closing a file

O/P

<_io.TextIOWrapper name=’sample.txt’ mode=’r’ encoding=’cp1252′>

Make sure that you are opening a file that already exists or else PVM will be against you.



Reading from a file in Python

Once we open a file in read mode, we can read the content from the file. This can be done using read(), readline() and readlines() functions in Python.

Let’s see how,

sample.txt

Hello World in line 1
Hello World in line 2
Hello World in line 3
Hello World in line 4
Hello World in line 5
fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
data = fp.read() # to read all content from file
print(data)
f.close() # closing a file

O/P

Hello World in line 1
Hello World in line 2
Hello World in line 3
Hello World in line 4
Hello World in line 5

read() function in Python is used to read all content from the given file and return it as a string.

read() function also gives us the utility to read the first ‘n’ characters from the given file,

fp.read(n)

where, ‘n’ is the number of bytes to read from beginning of file.

Other option to read a file is using readline() function.

readline() function in Python is used to read the first line from the given file and return it as a string.

fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
data = fp.readline() # to read one line from file
print(data)
f.close() # closing a file

O/P

Hello World in line 1



readlines() function in Python is another function used to read the entire content from the given file and return it as a list.

fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
data = fp.readlines() # to read all content from file
print(data)
f.close() # closing a file

O/P

[‘Hello World in line 1\n’, ‘Hello World in line 2\n’, ‘Hello World in line 3\n’, ‘Hello World in line 4\n’, ‘Hello World in line 5\n’]

Like read(), both readline() and readlines() functions also support reading first ‘n’ lines from a file.

Closing a file in Python

A file that is opened is eligible to be closed. This can be done using close() function in Python. It is the best practice to close a file once its usage is done to avoid any ambiguity or file corruption. It could happen while working with multiple files.

f = open('sample.txt', 'r') # opening a file
f.close() # closing a file


Writing an existing file in Python

If you want to add some content in an existing file, there are two ways to achieve this.

“a” – Append – will append to the end of the file

“w” – Write – will overwrite any existing content

fp = open('sample.txt', 'a') # opening a file sample.txt in append mode
fp.write('Say No Hello world') # to append a content to file
f.close() # closing a file

O/P (sample.txt)

Hello World in line 1
Hello World in line 2
Hello World in line 3
Hello World in line 4
Hello World in line 5
Say No Hello world

fp = open('sample.txt', 'w') # opening a file sample.txt in write mode
fp.write('Say No Hello world') # to write a content to file
f.close() # closing a file

O/P (sample.txt)

Say No Hello world

Observe how previous content of file was overridden by the new one.

Creating a new file in Python

To create a new file in Python, we should use the open() method, with one of the following parameters:

“x” – Create – will create a file, returns an error if the file exist

“w” – Write – will create a file if the specified file does not exist

“a” – Append – will create a file if the specified file does not exist

f = open("sample.txt", "x")
OR
f = open("sample.txt", "w")
OR
f = open("sample.txt", "a")

Checking if file exists in Python or not

In order to do file operations, if we want to pre-check whether that particular file exists or not, we can make use of os module in python.

import os
if os.path.isfile('sample.txt'):
    f = open('sample.txt', 'r')
    print(f.read())
else:
    print('Given file does not exists.')

Given method os.path.isfile(filename), returns True if files exists in the given path else it returns False.



seek() and tell() function in Python

tell() function in Python is used to find the current position of the file pointer from the beginning in the given file.

f.tell()

seek() function in Python is used to bring the file pointer to the given specified position.

f.seek(offset, position)

offset: It represents how many bytes to move.

position: It represents from which position file pointer should move.

Let’s see their application,

Consider a file sample.txt has following content in it,

Hello World
fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
print(fp.read())
print(fp.tell()) # prints 11 as file pointer comes at the last position while reading file
fp.seek(2) # pulling file pointer to second position
print(fp.tell()) # prints 2 as we just seek file pointer to second position
print(fp.read()) # read content from position 2 (0-based index)

O/P

Hello World
11
2
llo World

That’s all in “File Handling in Python”.

NEXT TUTORIAL >> with statement in Python

Tags: binary file handling in python class 12binary file handling in python class 12 questions and answersbuffering in file handling in pythondata file handling in python class 12data file handling in python class 12 mcqdata file handling in python class 12 notes pdfdata file handling in python class 12 questions and answersdefine file handling in pythonexcel file handling in pythonexplain file handling in pythonfile handling in pythonfile handling in python 2.7file handling in python 3file handling in python class 12file handling in python class 12 important questionsfile handling in python class 12 mcqfile handling in python class 12 notesfile handling in python class 12 notes pdffile handling in python class 12 pptfile handling in python class 12 questions and answersfile handling in python class 12 solutionsfile handling in python class 12 sumita arora pdffile handling in python documentationfile handling in python examplefile handling in python examplesfile handling in python exercisesfile handling in python hindifile handling in python in hindifile handling in python in tamilfile handling in python jupyter notebookfile handling in python mcqfile handling in python mcq class 12file handling in python notes class 12file handling in python pdffile handling in python pptfile handling in python programmingfile handling in python programsfile handling in python questionsfile handling in python readfile handling in python tutorialfile handling in python w3schoolsfile handling questions in python for class 12file handling questions in python for class 12 mcqfile management in python 3file operations in python exampleshow to do file handling in pythonhow to handle files in pythonjson file handling in pythonmcq on file handling in pythonmcq on file handling in python class 12program for file handling in pythonquestions on file handling in pythonquestions on file handling in python class 12what is data handling in pythonwhat is file handler in pythonwhat is file handling in pythonwhy do we need file handling in pythonwhy we need file handling in pythonwith in file handling in pythonxml file handling in python
  • Previous seek() and tell() function in Python
  • Next User Defined Exceptions in Python with Examples

Leave a Reply Cancel reply

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

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.