Python has several functions for updating, creating, reading and deleting files. Major function for file handling is open() This function will open a file for reading content from file writing content to file or append some content to a file.
Any file we want to use firstly we will open this file with open() function it takes 2 parameters first File Path and second file opening mode. File opening modes are given below.
- “r” – Read Open a file for reading error if file not exist
- “a” – Append Open a file for appending, Create a file if not exist
- “w” – Write Open a file for writing, Create a file if not exist
- “x” – Create a New file, return an error if file already exist
“t” and “b” can also be used for open a file in text or binary mode.
How to write
file = open("demo.txt")
This code will open a file in read and text mode because “r” and “t” are default mode of Open() function.
read() function
After successfully opening a file we can read its data with read() function.
file = open("demo.txt")
print(file.read())
This code will read a file named “demo.txt” and print all its data. If you want to read only some part of data you can pass a parameter to read() function that how many character you want to read from file.
Read Lines
readline() function will read a single line of opened file. Call this function again and again for next line read like.
file = open("demo.txt")
print(file.readline())
print(file.readline())
This code will read first 2 lines of files.
With the help of loop you can read all lines of opened file like below given method.
file = open("demofile.txt")
for single_line in file:
print(single_line)
This code will read the opened file line by line and print it.
Write to a file
Open file in “w” or “a” mode to write in a file or append some content in file like.
file = open("demo.txt", "a")
file .write("Now the file has more content!")
In this code program will open a file in append mode and add some new content to file existing content will not be changed.
file = open("demo.txt", "a")
file .write("Now the file has more content!")
In this code program will open a file in write mode and add some new content to file existing content will be overwrite.
Note: Both of above given code will also create a new file if file not exist.
Close a file
A file should always closed if you have finished working on it, if you will not close the file all the changes may be lost. to close a file below given code will work.
file = open("demo.txt", "a")
file.write("Now the file has more content!")
file.close()
In this code “file.close()” function will close the opened file after all the process is done