How to open and close a file in Python

There might rise a situation where one needs to interact with external files with Python.Python provides inbuilt functions for creating, writing and reading files.
in this article, we will be discussing how to open an external file and close the same using Python.

Opening a file in python:

There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode).

Note: The file should exist in the same directory as the Python script, otherwise, full address of the file should be written.

Syntax: File_object = open(“File_Name”, “Access_Mode”)



Parameters:

  • File_Name: It is the name of the file that needs to be opened.
  • Access_Mode: Access modes govern the type of operations possible in the opened file. The below table gives the list of all access mode available in python:
    Operation Syntax Description
    Read Only r Open text file for reading only.
    Read and Write r+ Open the file for reading and writing.
    Write Only w Open the file for writing.
    Write and Read w+ Open the file for reading and writing. Unlike “r+” is doesn’t raise an I/O error if file doesn’t exist.
    Append Only a Open the file for writing and creates new file if it doesn’t exist. All additions are made at the end of the file and no existing data can be modified.
    Append and Read a+ Open the file for reading and writing and creates new file if it doesn’t exist. All additions are made at the end of the file and no existing data can be modified.

Example 1:
In this example, we will be opening a file to read-only. The initial file looks like below:

Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

# open the file using open() function
file = open("sample.txt"
    
# Reading from file 
print(file.read()) 

chevron_right


Here we have opened the file and printed its content.

Output:

Hello Geek!
This is a sample text file for the example.

Example 2:
In this example, we will be appending new content to the existing file. So the initial file looks like below:

Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

# open the file using open() function
file = open("sample.txt", 'a'
    
# Add content in the file 
file.write(" This text has been newly appended on the sample file")

chevron_right


Now if you open the file you will see the below result,
Output:



Example 3:
In this example, we will be overwriting the contents of the sample file with the below code:

Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

# open the file using open() function
file = open("sample.txt", 'w'
    
# Overwrite the file 
file.write(" All content has been overwritten !")

chevron_right


The above code leads to the following result,
Output:

Closing a file in Python:

If you notice, we have not closed any of the files that we operated on in the above examples. Though Python automatically closes a file if the reference object of the file is allocated to another file, it is a standard practice to close an opened file as a closed file reduces the risk of being unwarrantedly modified or read.

Python has a close() method to close a file. The close() method can be called more than once and if any operttion is performed on a closed file it raises a ValueError.
The below code shows a simple use of close() method to close an opened file.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# open the file using open() function
file = open("sample.txt"
    
# Reading from file 
print(file.read()) 
  
# closing the file
file.close()

chevron_right


Now if we try to perform any operation on a closed file like shown below it raises a ValueError:

filter_none

edit
close

play_arrow

link
brightness_4
code

# open the file using open() function
file = open("sample.txt"
    
# Reading from file 
print(file.read()) 
  
# closing the file
file.close()
  
# Attempt to write in the file 
file.write(" Attempt to write on a closed file !")

chevron_right


Output:

ValueError: I/O operation on closed file.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Developer with a dream

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.