File Handling in Python
In this topic, we will learn about file handling in Python programming language. We can perform various tasks on files like read, write, add, etc.
Real-life programming you will not use too much but his concept becomes important in real-life programming when we manage our databases through the terminal. We work with root-level files within the database. This concept will also come in handy when learning Linux. If you aim to become a Python developer, you’ll need to perform these tasks frequently throughout your career. Let’s understand what this is through code.
1. Read the file:
Before we can perform any operations on a file, we must first open it. Python provides the open() function to open a file. It takes two arguments: the name of the file and the mode in which the file should be opened.
Syntax & Code:
f = open("your file name", "mode") #syntax
f = open('myfile.txt', 'r') #code
Once we have a file object, we can use various methods to read from the file. The read() method reads the entire contents of the file and returns it as a string.
f = open('myfile.txt', 'r') #folder must be create in root-level directory
contents = f.read()
print(contents)
If the file is located in a different location we will have to specify the file path like this:
f = open("D:\\myfiles\cybercript.txt", "r")
print(f.read())
Readlines:
You can return one line by using the readline() method:
f = open("demofile.txt", "r")
print(f.readline())
There are sevaral types of mode. Let’s see the all types:
- “r” – Read – Default value. Opens a file for reading, error if the file does not exist
- “a” – Append – Opens a file for appending, creates the file if it does not exist
- “w” – Write – Opens a file for writing, creates the file if it does not exist
- “x” – Create – Creates the specified file, returns an error if the file exists
In addition, you can specify if the file should be handled as binary or text mode
- “t” – Text – Default value. Text mode
- “b” – Binary – Binary mode (e.g. images)
2. Writing to a File:
Syntax & Code:
f = open('file name', 'mode')
f = open('myfile.txt', 'w')
f.write('Jai Shree Ram!')
Keep in mind that writing to a file will overwrite its contents. If you want to append to a file instead of overwriting it, you can open it in append mode.
f = open('myfile.txt', 'a')
f.write('Hello, world!')
Closing the file:
It is important to close a file after you are done with it. This releases the resources used by the file and allows other programs to access it. Closing the file is always best practices and makes a good python developer.
f = open('myfile.txt', 'r')
# ... do something with the file
f.close()
Open file using “with” statement:
Alternatively, you can use the with a statement to automatically close the file after you are done with it.
with open('myfile.txt', 'r') as f:
# ... do something with the file
When we open any .txt file it by default open in read mode and text mode. So, we can write this program like this:
# both are same
f = open("demofile.txt")
f = open("demofile.txt", "rt") # "rt" is default
Create a New File:
f = open("myfile.txt", "x") # Result: a new empty file is created!
Local and Global Variables in Python.
n this topic we will learn about local and global variables in Python programming language. If this concept is not….
I hope you understand “File Handling in Python”. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀