Python Tutorial

Opening and Closing a File in Python Using open() and close() Method

Python File Open Using open() method

The open() method is the most important function in Python for interacting with files. The filename and mode arguments are sent to the open() method. There are four alternative ways to open a file (modes):

  • "r" - Read: Default value. It will open a file for reading, error if the file does not exist.

  • "a" - Append: It will open a file for appending, creates the file if it does not exist.

  • "w" - Write: It will open a file for writing, creates the file if it does not exist.

  • "x" - Create: It will create a specified file and returns an error if the file exists. You can also indicate whether the file should be processed in binary or text format.

  • "t" - Text: Default value of the Text mode.

  • "b" - Binary: Binary mode 

f = open("demo_file.txt")

Python Close File Using close() method

The close() command terminates all the resources in use and frees the system of this particular program.


f = open("wscfile.txt", "r")




C:\Users\My Name>python
Hello! Welcome to wscfile.txt
This file is for testing purposes.
Good Luck!
Did you find this article helpful?