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.

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, creating the file, writing a file, reading the file, and deleting the file. file handling is the most important part of any web application. Most important function for file handling is open() function.

open () function takes 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 takes two parameters.

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

Open a file

To open a file for reading use open().

f = open("myfile.txt")

The above code is the same as.

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

r for reading and t for text.

Note: Make sure you will get an error if the file exists.

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

Python Variables with Examples
Python File Read

Related Posts