Introduction to File Handling
•File Operations
•Directories
File Handling
Files are named locations on disk to store related information. They are used to permanently store data in a non-volatile memory (e.g. hard disk).
- Since Random Access Memory (RAM) is volatile, we use files for future use of the data by permanently storing them.
- File handling provides a mechanism to store the output of a program in a file and to perform various operations on it.
File Types
Text files
In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default. Text file has extension .txt.
Binary files
In this type of file, there is no terminator for a line and the data is stored after converting it into machine understandable binary language. Binary files have an extension .bin.
File Operation
In Python, a file operation takes place in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
File Handling Method
Python provides the open() function which accepts two arguments, file name and access mode in which the file is accessed. The function returns a file object which can be used to perform various operations like reading, writing, etc.
The syntax to use the open() function—-
file object = open(<file-name>, <accessmode>, <buffering>)
The files can be accessed using various modes like read, write, or append.
The following are the details about the access mode to open a file.
SN | Access mode | Description |
1 | r | It opens the file to read-only. The file pointer exists at the beginning. The file is by default open in this mode if no access mode is passed. |
2 | rb | It opens the file to read only in binary format. The file pointer exists at the beginning of the file. |
3 | r+ | It opens the file to read and write both. The file pointer exists at the beginning of the file. |
4 | rb+ | It opens the file to read and write both in binary format. The file pointer exists at the beginning of the file. |
5 | w | It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file. |
6 | wb | It opens the file to write only in binary format. It overwrites the file if it exists previously or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file. |
7 | w+ | It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous file if one exists whereas r+ doesn’t overwrite the previously written file. It creates a new file if no file exists. The file pointer exists at the beginning of the file. |
8 | wb+ | It opens the file to write and read both in binary format. The file pointer exists at the beginning of the file. |
9 | a | It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name. |
10 | w | It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file. |
11 | ab | It opens the file in the append mode in binary format. The pointer exists at the end of the previously written file. It creates a new file in binary format if no file exists with the same name. |
12 | a+ | It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It creates a new file if no file exists with the same name. |
13 | ab+ | It opens a file to append and read both in binary format. The file pointer remains at the end of the file. |
File Handling Method Contd…
To open a file named “file.txt” (stored in the same directory) in read mode and printing its content on the console.
#opens the file file.txt in read mode
fileptr = open(“file.txt”,”r”)
if fileptr:
print(“file is opened successfully”)
Output:
<class ‘_io.TextIOWrapper’>
file is opened successfully
The close() method
Once all the operations are done on the file, we must close it through our python script using the close() method. Any unwritten information gets destroyed once the close() method is called on a file object.
We can perform any operation on the file externally in the file system is the file is opened in python, hence it is good practice to close the file once all the operations are done.
The syntax to use the close() method is —
fileobject.close()
Example
# opens the file file.txt in read mode
fileptr = open(“file.txt”,”r”)
if fileptr:
print(“file is opened successfully”)
#closes the opened file
fileptr.close()
File Handling Method Contd…
Reading the File
To read a file using the python script, the python provides us the read() method. The read() method reads a string from the file. It can read the data in the text as well as binary format.
The syntax of the read() method is —-
fileobj.read(<count>)
Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If the count is not specified, then it may read the content of the file until the end.
Reading from a file
There are three ways to read data from a text file.
1. Using read()
2. Using readline()
3. Using readlines()
Files
read() :
The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.
File.read([size])
Where, size is optional. The number of bytes to return. Default -1, which means the whole file.
Example: #opening file in reading mode
file1 = open(“mydata.txt”,”r”)
print(“Output of read()”)
print(“—————————–“)
#To read entire file using read()
print(file1.read())
file1.close() # closing the file
To run this program,
•Create new file using notepad.
•Type some content in the file.
•Save the file with name – mydata.
•Location of mydata file and program must be the same.
•If you save the mydata file at desktop, then save the python file also on desktop.
Example: Reading 7 character using read(7)
#opening file in reading mode
file1 = open(“mydata.txt”,”r”)
print(“Output of read()”)
print(“—————————–“)
#print(“Output of read(7)”)
print(file1.read(7))
file1.close()
readline() :
The readline() method returns one line from the file. You can also specified how many bytes from the line to return, by using the size parameter
Syntax: File.readline([size])
Where, size is optional. The number of bytes from the line to return. Default -1, which means the whole line.
Example 1:
file1 = open(“mydata.txt”,”r”)
print(“Calling readline() to return the first line only:”)
print(file1.readline())
file1.close() # closing the file
Example:
print(“Return only the six first bytes from the first line:”)
print(file1.readline(6))
readlines():
Reads all the lines and return them as each line a string element in a list.
Syntax: file.readlines(hint)
Where, hint is optional. If the number of bytes returned exceed the hint number, no more lines will be returned. Default value is -1, which means all lines will be returned.
Example 1:
file1 = open(“mydata.txt”,”r”)
print(“Return all lines in the file, where each line is an item in the list:”)
print(file1.readlines())
file1.close() # closing the file
Example 2: Do not return the next line if the total number of returned bytes are more than 10:
file1 = open(“mydata.txt”,”r”)
print(“Do not return the next line if the total number of returned bytes are more than 10:”)
print(file1.readlines(10))
file1.close() # closing the file
Redirecting the output:
We can redirect the output from output screen to a file by specifying the file object in print().
•Redirecting text to a file
print(“text”,file=file_object)
•Redirecting variable value to a file
print(var_name, file=file_object)
#Writing output to a file
f = open(“output.txt”, “w”)
r=5
a=3.14*r*r
print(“Area=”, a, file=f)
print(“New line.”, file=f)
f.close()
#Writing output to a file with more result
ch=’y’
f = open(“output.txt”, “w”)
while ch==’Y’ or ch ==’y’:
print(“Enter radius”)
r=float(input())
a=3.14*r*r
print(“Area=”, a, file=f)
print(“enter your choice”)
ch=input()
f.close()
Writing to a file
There are two methods to write in a file.
1. Using write()
2. Using writeline()
Write():
The write() method writes a specified text to the file. Where the specified text will be inserted depends on the file mode and stream position. A file can be written in two mode:
- “a”: The text will be inserted at the current file stream position, default at the end of the file.
- “w”: The file will be emptied before the text will be inserted at the current file stream position, default 0. The contents of existing file will be overwritten.
Note:
- If file does not exist, the new file will be created using “a” or “w” mode.
- If you want to create a new file, then use “a” or “w” mode.
- If you want to append the contents at the end of the existing file, use “a” mode.
- If you want to overwrite the content of an existing file, use “w” mode.
Note: “x” mode is similar to “w ” mode.
- For “x ” mode, if the file exists, raise FileExistsError.
- For “w” mode, it will simply create a new file or overwrite the existed file.
Syntax: file.write(byte)
Where, byte is the text or byte object that will be inserted.
Example 1: Open the file with “a” mode for appending, then add some text to the file:
#opening file in read mode to see contents of original file
f = open(“mydata.txt”,”r”)
print(“Original File:”)
print(“———————————————–“)
print(f.read())
f.close()
#opening file in append mode to write into file
f1 = open(“mydata.txt”,”a”)
#writing into file
f1.write(“This line inserted today”)
f1.close()
#open and read the file after the appending:
print(“File After appending the content to the file-“)
print(“———————————————–“)
f = open(“mydata.txt”, “r”)
print(f.read())
f.close()
creating a new file named new_file.txt and typing the content using keyboard
f1 = open(r”C:\Users\nielit\Documents\new_file.txt”,”w”)
#writing content from keyboard in file
s=input(“Enter text to be inserted in file:”)
f1.write(s)
f1.close()
#open and read the file after the appending:
print(“File After writing the content to the file-“)
print(“———————————————–“)
f = open(r”C:\Users\nielit\Documents\new_file.txt”, “r”)
print(f.read())
f.close()
Writelines()
The writelines() method writes the items of a list to the file. Where the texts will be inserted depends on the file mode and stream position. It is used to write more than one line to the file. The file can be opened in two modes:
- “a”: append mode
- “w”: write mode
Example 2: Creating a new file named writelines_ex.txt and typing the content using keyboard
f1 = open(“writelines_ex.txt”,”w”)
#writing content from keyboard in file
s=input(“Enter text to be inserted and press enter key to insert the content in the file:”)
f1.writelines(s)
f1.close()
#open and read the file after the writing:
print(“File After writing the content to the file-“)
print(“———————————————–“)
f = open(“writelines_ex.txt”, “r”)
print(f.read())
f.close()
Example 1: Open the file with “a” for appending, then add a list of texts to append to the file:
#Open the file with “a” for appending, then add a list of texts to append to the file:
f = open(“demofile3.txt”, “a”)
#demofile3 file will now be created where this program is stored
f.writelines([“See you soon!”, “Over and out.”])
f.close()
#open and read the file after the appending:
f = open(“demofile3.txt”, “r”)
print(f.read())
The difference between Write() and WriteLine() method is based on new line character.
- write(arg) expects a string as argument and writes it to the file. If you provide a list of strings, it will raise an exception.
- writelines(arg) expects an iterable as argument (an iterable object can be a tuple, a list, a string). Each item contained in the iterator is expected to be a string.
seek () function
The seek() method sets the current file position in a file stream. The seek() method also returns the new position.
Syntax: file.seek(offset)
Where, offset is required. Offset is the number representing the position to set the current file stream position.
#Using seek method to place cursor at 4th position and then reading:
f = open(“demofile3.txt”, “r”)
print(“Original Content:”)
print(f.read())
print(“—————————————“)
print(“Reading the content from 4th position:”)
f.seek(4)
print(f.readline())
f.close()
Tell()
The tell() method returns the current file position in a file stream.
Syntax: file.tell()
It has no parameter.
Example: Open the file and check the cursor position:
f = open(“demofile3.txt”, “r”)
print(“Current Location of cursor”,f.tell())
print(f.readline())
print(“Updated Location of cursor after reading”,f.tell())
Python os module
The os module provides us the functions that are involved in file processing operations like renaming, deleting, etc.
Let’s look at some of the os module functions.
Renaming Files
The os module provides us the rename() method which is used to rename the specified file to a new name.
The syntax to use the rename() method is…
rename(?current-name?, ?new-name?)
Example:
import os;
#rename file2.txt to file3.txt
os.rename(“file2.txt”,”file3.txt”)
Removing the file
The os module provides us the remove() method which is used to remove the specified file.
The syntax to use the remove() method is–
remove(?file-name?)
Example:
import os;
#deleting the file named file3.txt
os.remove(“file3.txt”)
Creating the new directory
The mkdir() method is used to create the directories in the current working directory.
The syntax to create the new directory is
mkdir(?directory name?)
Example:
import os;
#creating a new directory with the name new
os.mkdir(“new”)
Changing the current working directory
The chdir() method is used to change the current working directory to a specified directory.
The syntax to use the chdir() method is
chdir(“new-directory”)
Example:
import os;
#changing the current working directory to new
os.chdir(“new”)
Changing the current working directory
The chdir() method is used to change the current working directory to a specified directory.
The syntax to use the chdir() method is
chdir(“new-directory”)
Example:
import os;
#changing the current working directory to new
os.chdir(“new”)
The getcwd() method
This method returns the current working directory.
The syntax to use the getcwd() method is
os.getcwd()
Example:
import os;
#printing the current working directory
print(os.getcwd())