Namaste Coders π©βπ»
In this article, we will discuss file handling in Python.
Variables are a fine way to store data while your program is running, but if you want your data to persist even after your program has finished, you need to save it to a file. You can think of a fileβs contents as a single string value, potentially gigabytes in size.
Files are used for permanent storage. We could also use a relational database but it is complex and uses tables. In comparison to it, files are way easier.
File handling seems to be difficult in other languages but, in python, it is easy to use π and understand. Also, it is short to write π€ . Python treats files of two types π
- Character Mode: It is in simple characters and digits format. A normal text file.
- Binary Mode: these are the file format used to store media like images.
Syntax
file = open(file_path , file_mode)
file.close()
Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun.
File Operations
We can perform various operations on file using Python like open,write,read and many more. While working with files we need to specify mode in which we want to use file.
- r: Opens file for reading
- w: Opens the file for writing but it overwrites the data. Creates a new file if it does not exist
- x: Opens a file for exclusive creation. If the file already exists, the operation fails.
- a: Opens the file in append mode i.e, it adds data at the end of file keeping existing data.
- t: Opens file in text mode.
- b: Opens file in binary mode.
Steps to work on a file
- First, we need to open a file in the desired mode
- After work is completed, it is mandatory to close the file to release all its resources.
Read Mode
It only allows you to read a file. It will throw an error if you try to open a non existing file in read mode.
Syntax:
file = open(file_path , "r")
test.txt file π Welcome in test file
# opening test.txt file in read mode
# specify path in terms of main directory you are
# In this example it is inside PythonCodes in file folder
file = open("./test.txt", "r")
content=file.read()
print(content)
# closing a file is mandatory
file.close()
Read Mode Operations
There are various functions associated with file pointers. Suppose we open a file in variable f then various functions are as ππ
- f.readline() :prints first line. If we will again run it then it will print the next line.
- f.readline(num): if we specify the number of characters to be printed then it prints that number of characters.
- f.readlines() : It provides all the lines in list format as output.
- f.seek(num): It brings the cursor to the number sent as a parameter.
- f.tell() : It tells current position of the pointer.
file = open("./test.txt", "r")
# it will print first four characters
print(file.read(4))
# it will print next four characters
print(file.read(4))
# closing a file is mandatory
file.close()
#output:-
#Welc
#ome
Example
file = open("./test.txt", "r")
# it will print first line
print(file.readline())
# it will print next line
print(file.readline())
# closing a file is mandatory
file.close()
#output:-
#Welcome in test file
#We are learning python programming
Example of readlines()
file = open("./test.txt", "r")
# using f.readlines()
print(file.readlines())
# closing a file is mandatory
file.close()
#output:-
#['Welcome in test file\n', 'We are learning python programming\n', 'hope you will have fun in #learning!']
Write Mode
Write mode allows us to add the data to the file. It overrides the pre-written data and adds the content mentioned in the write() function. If the file_name is not present then it creates an empty file at the location mentioned.
Syntax:
file = open(file_path , "w")
Example of writing in a file is as follows
file = open("./test.txt", "r")
print("----before writing---")
print(file.read())
#updating file variable
file=open("file/test.txt", "w")
file.write("this is written using python")
# writing in a file
file.close()
output on terminal
----before writing---
Welcome in test file
We are learning python programming
hope you will have fun in learning!
Now on checking test.txt this is written using python π
All other data has been overwrite.
On checking the file content is ππ²
this is written using python
Append Mode
We will be using append mode to add data without overriding the existing data. It also creates an empty file, if the file does not exist.
Syntax:
file = open(file_path , "a")
file = open("file/test.txt", "r")
print("----before writing---")
print(file.read())
file=open("file/test.txt", "a")
file.write("\nPython is an amazing language")
# writing in a file
file.close()
output on terminal π
----before writing---
this is written using pythonPython is an amazing language
Now updation in test.txt file π
this is written using python
Python is an amazing language
It has appended context as mentioned in the python program. We can write multiple lines using the writelines() function.
Binary Mode
Binary mode is required to work on media files (mp3, png, pdf, jpg)
Syntax
#to open in read mode
file = open(file_path , "rb")
#to open in write mode
file = open(file_path , "wb")
Example
# to open an image we have to use rb for binary file and r for read
file = open("file/pic.jpg", "rb")
print(file.read())
file.close()
#output:
#It will give image in bytes.
a Smarter way to work with files
It might be the case that one may forgets to close the file. To solve this issue we have another way of handling files using with keyword which closes files automatically when work is over.
It provides block scope to the statements. When we come out of the scope, files are closed.
with open('file/test.txt','w') as f:
f.write("added using with key word")
with open('file/test.txt','r') as f2:
print(f2.read())
#Output
#added using with key word
Interview question to copy content from one file to another ππ
The End
I hope you enjoyed the article and had a good learning experience.
Follow for more articles and keep sharingπ©
Keep coding