File Handling

File

Handling

In Python


What is File Handling in Python?

File handling in Python is the process of reading, writing and managing files on the computer’s file system using built-in functions and methods.


In Python, a file operation takes places in the following order:

 

1. Open a file

2. Read or write (perform operation)

3. Close the file


Opening Files

Python has a built-in open() function to open a file


You can either write the file name if name is unique, else you can write whole file path.

 

There are four different methods (modes) for opening a file:

 

“r” – Read

Default value. Opens a file for reading, error if the file does not exists.

 

“a” – Append

Opens a file for appending, creates the file if it does not exists.

 

“w” – Write

Opens a file for writing, creates the file if it does not exists.

 

 

“x” – Create

Creates the specified file, returns an error if the file exists.

 

Reading Files

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


‘r’ – it tells the file is in reading mode.

 

Writing Files in Python

 

Writing a string or sequence of bytes is done using the write() method.


‘r’ – it tells the file is in reading mode.

 

Closing Files

It is done using the close method available in Python.


Previous Next

Start Your Data Journey Today With MSAInfotech

Take the first step towards data-led growth by partnering with MSA Infotech. Whether you seek tailored solutions or expert consultation, we are here to help you harness the power of data for your business. Contact us today and let’s embark on this transformative data adventure together. Get a free consultation today!

We utilize data to transform ourselves, our clients, and the world.

Partnership with leading data platforms and certified talents

FAQ Robot

How Can We Help?

Captcha

MSA Infotech