Menu Close

Python File Handling

In this tutorial, you will learn about Python file handling. In file handling, you will learn to create files, write files, delete files, and some of the most important methods of the file object with the help of examples.

Note:- To understand this, you should have basic knowledge of Python programming.

Table of Contents

What is file?

A file is named location on the hard disk which is stores related information. A file permanently stores data in non-volatile memory (hard disk).

What is File Handling?

File handling in Python is the process of working with the file, create the file, write a file, read the file and delete the file. file handling is the most important part of any web application. Most important function for file handling is open() function.

open () function take two parameters; filename, modes.

There are four different modes in file handling for opening a file.

  • ‘r’ – Read: Default value. Open a file for reading, error if the file does not exist.
  • ‘w’ – Write: Open a file for writing, create the file if does not exist.
  • ‘x’ – Create: Create a specific file, return an error if the file exists.
  • ‘a’ – Append: Open a file for appending, create the file if the does not exist.

For binary mode.

  • ‘t’ – Text: Open file for text mode.
  • ‘b’ – Open file in binary mode.

Syntax

open(filename, mode)

Parameters

Python open function take two parameters.

  • filename- filename refers to the name of the file.
  • mode – mode refers to the mode described above.

Open a file

To open file for reading use open().

f = open("myfile.txt")

Above code is same as.

f = open("myfile.txt","rt")

r for read and t for text.

Note: Make sure you will be get an error, if the file exist.

Conclusion

So, In this Python guide, we have seen all about Python file handling basic which means what is a file, what is the file handling as well as have seen how to open a file in reading mode. In the next tutorial, we will learn more about Python file handling with practical examples.

If you like this python file handling article, please share and keep visiting for further Python tutorials.

Reference:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts