Python for Beginners – Part 4 – File handling in Python

Hi All,
As we started series on Python for beginners today we will continue on our fourth article. In this article we will discuss methods to perform common / basic file operations.
In last three articles we discussed
Types of file supported in Python:
- Text files
- Binary files
In Python following are the order of file operations:
- Open a file
- Read or write (perform operations) – Interestingly for reading and writing file in Python we don’t need to import external library 🙂
- Close the file
Lets explore each operations.
Open a file:
- In python we open file using open() method
- open() returns file object
- syntax: file = open(filename, mode) where,
- filename: name of the file if file is in current directory. Or absolute path of file
- mode: Optional parameter. Possible values for mode are
Mode | Details |
r | read. This is default mode in case we didn’t specified mode parameter |
w | write. Existing content will be overwritten. New file will be created if specified file does not exists |
a | append the content to existing content in a given file. New file will be created if specified file does not exists |
r+ | Opens the file for both operations – reading and writing |
x | create. Creates the specified file either in current directory or on specified path. If specified file is already exists then returns an error |
Along with mode parameter we can also specify parameter for file type, whether file should be treated as text or binary file by specifying “t” or “b”
Opening the file:
#Following open() method will open file in read mode and returns file object
file = open(“c:\Prasham\Blogs\Python\pythonfileoperations.txt”, ‘rt’)
Reading the file: There are multiple ways to read the file.
Reading complete file as one string –
#read complete file – return one big string
print(file.read())
Reading file line by line –
#This will print every line one by one in the file
for each in file:
print (each)
#OR
data = file.readlines()
for line in data:
print(line)
Read single line at a time –
#reading one line at a time.
#reads the file till new line
print(file.readline())
Writing to the file: To write into file, we need to open file in write mode otherwise exception will be there – io.UnsupportedOperation: not writable
Overwriting the existing file –
#open file in write mode
file = open(“c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations.txt”, ‘w’)
#By default it overwrites to existing file
file.write(“Writing to file – This is again first line since it will overwrite the content of existing file”)
Append the new content to existing content of file –
#to append to the file, we need to open file in append mode
file = open(r”c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations.txt”, ‘a’)file.write(“Writing to file – This is second line”)
Writing multiple lines to file –
#writing multiple lines to file
file = open(“c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations.txt”, ‘a’)
#create array of lines
lines_of_text = [“a line of text”, “another line of text”, “a third line”]
file.writelines(lines_of_text)
file.close()
Crating a new file –
#creating a file. Returns error if file exists exception: FileExistsError
file = open(r”c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations_new.txt”, ‘x’)
Deleting the file: To delete file we import os module and use remove()
import os
os.remove(r”c:\Prasham\Blogs\Python\FileOperations\pythonfileoperations_new.txt”)
#We can also check if file exists or not
#check if file exists
if os.path.exists(“demofile.txt”):
os.remove(“demofile.txt”)
else:
print(“The file does not exist”)
Today, I’ll stop here. There are still more details to come for file handling, I’ll share in next article.
Thanks for reading 🙂 Sharing is caring 🙂
You must log in to post a comment.