This method is used to write text in the file.
This method is used to write multiple lines in the file.
3. Reading a File in Python
The read() method is used to read data from a file. To read the file, we have to open the file in read mode(r). We can read data from a file in Python in three different ways, with these three functions:
- read(): it will read the whole file
- readline(): This function will read one line at a time
- readlines(): This function will read all lines into a list.
Using the read() method in Python
Suppose we have a file named intellipaat_courses.txt, and we want to read the data from the file. The following code will help us to read the data from the file.
Example:
Output:
Explanation: We have opened the file named intellipaat_courses.txt, read the file with read(), and printed the data.
Using readline() method in Python
This method reads the file line by line.
Example:
Output:
Explanation: If the file contains two or more lines, then we will use this function to read the file.
Using readlines() method in Python
This function helps us to read all lines and put them into a list. Let’s
Example:
Output:
Explanation: Here, we opened intellipaat_courses.txt, used readlines() to store all lines in a list, and printed them efficiently without extra spaces.
4. Closing a File in Python
You can use the close() function to close an opened file in Python. We must close the file after opening it to release all the resources. This function also ensures that the changes made to the files must be saved before closing the file.
Syntax:
file = open(‘file.txt’, ‘r’)
file.close() # Close the file
Example:
Output:
Explanation: Here, the intellipaat_courses.txt file is opened, and “Python Files” is written to it, and then ensured that the file is closed properly, printing “File closed !!” after the file is closed.
- Using “with” Statement for Automatic File Closing
The ‘with’ statement is used to automatically close the file. It is the best practice to close the file in Python. It ensures that the file is closed after all the operations are completed, which reduces the risk of corruption of the file.
Example:
Output:
Explanation: Here, the file named intellipaat_courses.txt is opened. The data is read from the file, and the file is closed automatically after printing the data.
5. Deleting a File in Python
To delete a file in Python, you have to import the OS module and use the os.remove() function.
Example:
Output:
Explanation: Here, the file named intellipaat_courses.txt is deleted using the os.remove() function.
6. Copying a File in Python
To copy a file, use the shutil module, which provides efficient file operations.
Example:
Output:
Explanation: The file is opened in write mode (“w”) and modified using a try-finally block to ensure closure. The shutil.copy() method is used to copy the file to copied_courses.txt.
7. Handling the Binary Files in Python
While reading binary files like images, PDFs, or any executable files, we can use the “rb” (read binary) or “wb” (write binary) mode.
Example: Writing & Reading a Binary File
Output:
Explanation: A binary file binary_file.bin is created and written using “wb” mode. The file is read using “rb” mode, and the binary content is printed, which shows b’Hello’ as the output.
8. Renaming a File in Python
To rename a file in Python, we use the os.rename() function that helps in overwriting the existing filename with a new one whenever needed in a simpler manner.
Example: Creating & Renaming a File
Output:
Explanation: The file sample_file.txt is created and written using “w” mode. The os.rename() function renames sample_file.txt to renamed_sample.txt.
9. Checking if a File Exists in Python
Checking whether a file exists is very important when working with various files. In Python, we use the os.path.exists() method from the os module to check the existence of the file.
Example:
Output:
Explanation: The os.path.exists() method checks if intellipaat_courses.txt exists. If the file is present, it prints “File exists!”.
10. Appending to a File in Python
When we need to add some data to a file instead of rewriting the whole data again, we can append data to a file by using the ‘a’ mode with the open() function. This mode helps in adding new content at the end of the file without deleting existing data.
Example:
Output:
Explanation: The os.path.exists() method checks if intellipaat_courses.txt exists. If the file is present, it prints “File exists!”. Then, the ‘a’ mode in open() appends “Full Stack” to the file without deleting the already existing data and displays it.
Alternate Methods of File Handling in Python
The following are the other common methods of file handling in Python, along with their descriptions:

Method |
Description |
flush() |
Clears the internal buffer and writes data to the file immediately. |
seek(offset,from=SEEK_SET) |
Moves the file offset (pointer) to a specific position (start, current, or end). |
tell() |
It returns the current file location. |
writable() |
Check if the file can be written, then return True or False based on the condition. |
readable() |
Returns True if the file stream can be read, else returns False. |
rename() |
It helps us to rename the file. |
Advantages of File Handling in Python
Here are some of the advantages of file handling in Python:
- Data Persistence: Files store the data permanently, which ensures that the data is accessible even after the completion of the execution.
- Data Manipulation: Python allows users to perform file reading and writing and file update operations with high efficiency.
- Data Exchange: Python supports various file formats, including text files, CSV, JSON, and binary files, which enables simple data management procedures.
- Versatile: Python handles different file types, like text, CSV, JSON, and binary files, which allows easy manipulation of the data.
- Integration: File handling helps in integrating your external data sources, such as databases, which allow you to play with that data according to the project requirements.
Disadvantages of File Handling in Python
Here are some of the advantages of file handling in Python:
- Security: There are chances of the files getting easily updated, written, and copied from an external source, which would be a security risk. So there is a need to protect the file efficiently.
- Performance: Operations involving files are slower than data management from memory.
- Error handling: Users need to handle various errors during file handling because missing files or incorrect permissions, or unexpected failures could occur.
Get 100% Hike!
Master Most in Demand Skills Now!
Conclusion
In this tutorial, we covered essential file-handling operations like reading, writing, appending, and closing files, which are very important for efficiently handling the data. Python provides many built-in functions for performing these operations. While these are the basic fundamental concepts, Python also offers advanced techniques and libraries for specific use cases. If you’re eager to master them and take your skills to the next level, join our trending Python Course and also explore basic Python Interview Questions prepared by industry experts to improve your preparation.