7 File Handling Operations in Python Explained with Programming Examples
File handling is a very crucial concept in Any programming. The file is used to store the text data which can be used by your program.
Want to learn how to create, open read and write in Python?
Here is a complete file handling Python tutorial for you.
File Handling in Python
There are multiple operations to perform such as creating, reading, writing and updating file content.
Let’s see how to do those file handling in Python with open() function with programming examples.
How to Create a File in Python?
We are using open() built-in function to create a file.
This is the single open method that will create the file if it is not present.
To add content in the newly created file, you should open the file in write mode.
There are two arguments are passed to the open() build in function- the name of the file and mode the file (w+).
w – create the file in write mode
+ – create a file if it’s not present in the current directory.
Note: File will be created in the current directory (the directory where your Python code is running).
How to open the File in Python?
You can use the same code as I have mentioned for creating a file.
open("myFile.txt", "r") as fObj
How to Read File in Python?
First, open the file in reading mode “r” and then read the content from the file.
open("myFile.txt") as fObj data = fObj.read() print(data)
All the file contents will be saved in a single string object.
You can also use “with” statement with an open file.
with open("myFile.txt") as fObj: data = fObj.read() print(data)
There are multiple benefits of using “with” statement. We will see the benefits in the later part of this tutorial.
Now a day it has become standard practice opening file “with”
How to Read Line-by-Line File into List?
Rather than reading complete file text in a single string object, what if you want to read the file line-by-line?
with open("myFile.txt") as fObj: liData = fObj.readlines() print(liData)
Each line in the file will be saved as one element in the list. So the size of the list will be the same as the number of lines in the file.
Reading file in the list is very important when you want to manipulate the text in each line of the file. After reading file content in the list, you just need to loop over each element in the list and perform your desired operation.
Python provides multiple list operations which makes your work associated with the file operation even easier.
How to Write a File in Python?
Two operations. First, open the file and then write the text content in it.
File object has write() method associated with it to write the text in the file.
with open("myFile.txt", 'a+') as fOut: fOut.write("my data to add."+'\n')
- We are opening the file in “a+” mode so that, it will append the new content at the end of the file.
- The “\n” character is used to add the next in a new line.
How to Close a File in Python?
It is always good practice to close the file after using it.
Python code to close and delete the file object if you are not performing any file operation further.
open("myFile.txt", "r") as fObj #perform file operations fObj.close()
Use “with” statement while opening the file. You don’t need to explicitly close the file object. As soon as the pointer goes out of the with statement block, file object will be closed.
with open("myFile.txt", "r") as fObj: #perform file operations #file is closed automatically
How to Delete File in Python?
Many times you need to delete the file instead of closing it.
If you try to delete the file which is not present, it will throw an I/O error.
Always check the file existence. If the file present, delete it.
import os #delete file if it exists. if os.path.exists("yourFile.txt"): os.remove("yourFile.txt")
The “path” and “remove” objects are described in the os module. So, you have to import the “os” module.
What are the different File Modes in Python?
There are multiple modes to open the file.
“r” mode: Open the file in reading mode. The pointer will be assigned at the beginning of the file. It will throw an error if the file does not exist.
“r+” mode: Open the file for reading writing. The pointer will be assigned at the beginning of the file to read and write a file. It will throw an I/O error if the file not exist.
“w” mode: Open the file in write mode. The pointer will be assigned at the beginning of the file and it will overwrite all the contents in the file.
“w+” mode: Open the file in read-write mode. All the data in the existing file will be truncated (delete and throw away) and overwritten.
“a” mode: Open file in append mode. Instead of overwriting original content, in this mode, you can append the new content at the end of the file. If the file is not present, a new file will be created with the file name mentioned.
“a+” mode: Open the file in append mode. If the file does not exist, it will create a new file. It will append the new content at the end. Existing content in the file will be intact.
What is the default file mode?
If you don’t mention the file mode while opening the file, ‘r’ will be the default file mode
Best Practices for File Handing
1. Assign File Name to the Variable:
If you are reading and writing file multiple times, always create the variable for the file name. So you don’t need to assign file name every time in your program.
FILE_EMP = “empFile.txt”
with open(FILE_EMP) as fEmp: liEmp = fEmp.readlines()
Even in the future if you need to change the file name, you just have to change the new file name in a variable. Otherwise, you have to update the text file everywhere you have used through your project. Its time consuming and not good practice.
2. Choose Right Mode to Read, Write or Append File
If you don’t want your program to write the file, always open the file only for reading.
Opening file in write mode will erase the original content in the file and will add new content. If you want your program to append the new content at the end of the file, always open a file in append mode.
3. Closing file object after using it.
Otherwise, it is always a good choice to use” with” statement while opening the file.
Problems for File Handling in Python for Practice[Homework]
You can not learn all these file operations without writing code. So here are some of the problems you can practice and learn file handling.
1. Write a Python program to remove all the duplicates line from the file.
Hint: Read the file line-by-line in the list and find all the unique element in the list. Write back all the content from the list in the file.
2. Write a Python program to randomly select any line from the file.
Hint: Read the file line-by-line in the list and randomly select element from the list.
3. Write a Python program to add given line to file if it is not already there.
Hint: Read line-by-line file into the list. Search if the given text is present. If it is not there, append the new content inside the file as a new line.
4. Write a Python program to find the longest line in the file.
Hint: Hint mentioned in the above three problems is sufficient to solve this problem as well.
You can also submit your homework with me. I will share your program on our portal.
This is all about a complete tutorial for file handling in Python. You have learned to create, to open, to read and to write a text file. If you find any difficulty while handling file or Python code mentioned in this tutorial, write in the comment.
For further, explore reading and writing CSV file in Python.