File open and close in python

Python has a built-in function open() to open a file, it returns something called a file object. File object contain methods and attributes that can be used to collect information about the file you opened. They can also be used to manipulate said file.

Open a file in Python

Here filename is a string argument which specify filename along with it's path and filemode is also a string argument which is used to specify how file will be used i.e for reading or writing. And my_file is a file handler object also known as file pointer.



In the above example, open a text file called "my_file.txt" in reading only mode. The print its file name and file mode.

Close a file in Python

When you're done with a file, use close() to close it and free up the resources that were tied with the file and is done using Python close() method.


It is important to note that always make sure you explicitly close each open file, once its job is done and you have no reason to keep it open. Because there is an upper limit to the number of files a program can open. If you exceed that limit, there is no reliable way of recovery, so the program could crash.

The close() method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file. It is better to use a try...finally block.


In the above example, it is guaranteed that the file is properly closed even if an exception is raised, causing program flow to stop.

By using "with" statement is the safest way to handle a file operation in Python because "with" statement ensures that the file is closed when the block inside with is exited.


In the above example, you don't need to explicitly call the close() method. It is done internally.

Renaming and Deleting files in python

The OS module in Python provides a way of using operating system dependent functionality. OS module comes under Python’s standard utility modules. In order to use this module you need to import it first and then you can call any related functions.

Renaming a file in Python

os.rename(old_file_name, new_file_name)


Deleting a file in Python

 (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About