Thursday , November 21 2024
Python File Handling - Opening and Closing Files, Reading and Writing files

Python Files Handling

12 File Handling

Python File Handling

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

Functions used in File Handling

  • open()
  • close()
  • read()
  • write()
  • seek()
  • tell()

The key function for working with files in Python is the open() function.

  • The open() function takes two parameters; filename, and mode.

Types of Mode

  • “r” – Read – Default value. Opens a file for reading, error if the file does not exist
  • “w” – Write – Opens a file for writing, creates the file if it does not exist
  • “a” – Append – Opens a file for appending, creates the file if it does not exist
  • “r+” – Read + Write
  • “w+” – Create + Read + Write (Previous Data Erase)
  • “a+” – Create + Read + Write (Append Mode)

Open the file

  • fo = open(“itronix.txt”)
  • fo = open(“itronix.txt”,’r’)
In [1]:
fo = open('itronix.txt','r')  #file is not present so it will give error
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-1-2db04c7af943> in <module>
----> 1 fo = open('itronix.txt','r')  #file is not present so it will give error

FileNotFoundError: [Errno 2] No such file or directory: 'itronix.txt'

Write to file

  • if file not exist it will create the file
In [2]:
fo=open('itronix.txt','w')
fo.write("Welcome to Python Tutorials")
fo.close()

Read from file

In [3]:
fo=open('itronix.txt','r')
data=fo.read()
print(data)
Welcome to Python Tutorials

Read Only Parts of the File

In [4]:
fo=open('itronix.txt','r')
data=fo.read(7) #read first 7 characters
print(data)
Welcome

Read Line

  • You can return one line by using the readline() method:
In [5]:
fo=open('itronix.txt','r')
data=fo.readline()
print(data)
Welcome to Python Tutorials

Read Lines

  • You can return Line by Line in a List by using the readlines() method:
In [6]:
fo=open('itronix.txt','r')
data=fo.readlines()
print(data)
['Welcome to Python Tutorials']

Loop through the file line by line:

In [7]:
fo=open('itronix.txt','r')
for x in fo:
    print(x)
Welcome to Python Tutorials

Write in Append Mode

In [8]:
fo=open('itronix.txt','a')
fo.write("Learn Python from MachineLearning.org.in")
fo.close()
In [9]:
fo=open('itronix.txt','r')
data=fo.read()
print(data)
Welcome to Python TutorialsLearn Python from MachineLearning.org.in

Write+ Mode: Used for both read and write

In [10]:
fo=open('itronix.txt','w+')
fo.write("Welcome to Python Tutorials. ")
data=fo.read()
print(data)
fo.close()

Note: Data is written in file but it won’t read any single character because pointer is point at the end. so we need to move pointer to the starting postion with the help of seek() function

Seek(offset[, whence])

  • offset − This is the position of the read/write pointer within the file.
  • whence − This is optional and defaults to 0 which means absolute file positioning,
In [11]:
fo=open('itronix.txt','w+')
fo.write("Welcome to Python Tutorials. ")
fo.seek(0,0)
data=fo.read()
print(data)
fo.close()
Welcome to Python Tutorials. 

Tell() : used to find the total characters in file from starting position to pointer current position

In [12]:
fo=open('itronix.txt','w+')
fo.write("Welcome to Python Tutorials. ")
Length = fo.tell()
print("Total Characters in File:",Length)
fo.close()
Total Characters in File: 29

About Machine Learning

Check Also

Python MySQL Insert Into Table

Python MySQL Insert Into Table

4 Python MySQL Insert Into Table Python MySQL Insert Into Table¶To fill a table in …

Leave a Reply

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