File Handling in Python Last Updated 25-04-2024 240426 180346
File Handling in Python Last Updated 25-04-2024 240426 180346
➢ In text file data is stored in text format or string format (OR) it allows only strings.
Example: .txt, .csv, .json,…
➢ Text Files: Text file allows only string data or text.
➢ In binary file data is stored in bytes format (OR) it allows only bytes type. Example:
images, audio, video, etc.
Basic steps to work with files:
1. Open File
2. Reading/Writing – performing operation
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 1 of 34
3. Close File
File Handling:
➢ The key function for working with files in Python is the open() function.
➢ The open() function takes two parameters (arguments) ; filename, and mode.
Syntax:
file_object = open(file_name, access_mode=’r’)
• the file name is string containing the name of the file to open.
➢ "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)
Character Meaning
'x' open for exclusive creation, failing if the file already exists
➢ wb : Write Binary
➢ rb : Read Binary
➢ wt : Write Text
➢ rt : Read Text
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 2 of 34
➢ w : Write Text
➢ r : Read Text
➢ r+w : update
To open a file for reading it is enough to specify the name of the file:
f1 = open("demofile.txt")
The code above is the same as:
f1 = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify
them.
Note: Make sure the file exists, or else you will get an error.
Note: If the file is located in a different location, you will have to specify the file path, like
this:
Example:
Open a file on a different location:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 3 of 34
f2 = open("D:\\myfiles\welcome.txt", "r")
print(f2.read())
Example:
# Return the 5 first characters of the file:
f2= open("demofile.txt", "r")
print(f2.read(5))
Read Lines:
❖ You can return one line by using the readline() method:
Example:
#Read one line of the file:
f3 = open("demofile.txt", "r")
print(f3.readline())
Note: By calling readline() two times, you can read the two first lines:
Example:
#Read two lines of the file
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Note:
By looping through the lines of the file, you can read the whole file, line by line:
Example:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 4 of 34
#Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files:
❖ It is a good programming practice to always close the file when you are done with
it.
Example:
# Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 5 of 34
Example:
#Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w") # open() function returns file object
f.write("trying to overwrite the content")
f.close()
Example:
Create a file called "bs.txt":
f4 = open("bs.txt", "x")
print(“a new empty file is created”)
OUTPUT:
a new empty file is created
Example:
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Example:
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Deleting Folder:
To delete an entire folder, use the os.rmdir() method:
Example:
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 7 of 34
File handling in Python:
▪ Reading a file in Python can be done in a few ways.
▪ The most common way is to use the built-in function called open () function, which
returns a file object that can be used to read from the file.
In this example, we are opening a file called "file.txt" in read mode ("r"). We are using a
"with" statement to ensure that the file is properly closed when we are done with it.
The "read" method is then called on the file object, which returns the contents of the file as
a string.
CODE:
In this example, we are opening a file called "file.txt" in write mode ("w"). We are using a
"with" statement to ensure that the file is properly closed when we are done with it.
The "write()" method is then called on the file object, which writes the string "Hello, world!"
to the file.
In this example, we are opening a file called "file.txt" in append mode ("a"). We are using
a "with" statement to ensure that the file is properly closed when we are done with it.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 8 of 34
The "write" method is then called on the file object, which appends the string "This is
appended text." to the end of the file.
Key-note: It's important to note that when you open a file using the "open" function, you
can specify the mode in which you want to open the file (read, write, append, etc.).
Additionally, you can use the "close" method on the file object to manually close the file
once you're done with it, although using a "with" statement is generally preferred as it
automatically takes care of closing the file for you.
Note:
In Python, you can get information about a file's attributes (such as its size, modification
time, etc.) using the "os" module.
Here is an example program that demonstrates how to use the "os" module to get
information about a file:
Program:
import os
# Get the size of a file in bytes
size = os.path.getsize('file.txt')
print('File size:', size, 'bytes')
We then use the "getsize" function from the "os.path" module to get the size of the file
"file.txt". This function returns the size of the file in bytes, which we store in the "size" variable
and print it out along with a message.
Next, we use the "getmtime" function from the "os.path" module to get the last modified
time of the file "file.txt". This function returns the time as a number of seconds since the
epoch, which we store in the "mod_time" variable and print it out along with a message.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 9 of 34
Additionally, the "os" module provides a wide range of methods that allows you to get other
information about files on your system, such as the permissions set for the file or its owner.
These methods provide a powerful way to access and manipulate files in a Python
program.
-----------------------------------------------------------------------------------------------------------------------------------
Example python program - demonstrating how to access these file attributes in Python:
file = open('example.txt', 'r')
print('File name:', file.name)
print('File mode:', file.mode)
print('File closed?', file.closed)
-------------------------------------------------------------------------------------------------------
Method Description
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 10 of 34
writelines() Writes a list of strings to the file
Method Description
▪ seek() function is used to change the file pointer to a given specific position.
▪ File pointer is like a cursor, which defines from where data has to be read or written
into the file.
▪ Syntax:
▪ Fileobj.seek(offset,from_what)
▪ The reference point is defined by the “from_what” argument. It can have any one
the following values.
▪ 0 : sets the reference point at the beginning of a file, which is by default.
▪ 1 : sets the reference point at the current file position.
▪ 2 : sets the reference point at the end of the file.
➢ Note: In Python 3.x and above, we can seek from beginning only, if opened in text
mode.
➢ We can overcome from this by opening the file in ‘b’ mode (Binary mode)
➢ tell()
➢ tell() returns the current position of the file pointer from the beginning of the file.
Here's an example python program demonstrating how to access these file attributes in
Python:
In this example, we first open the file "example.txt" in read mode using the `open()` function
and store the resulting file object in the variable `file`.
We then access the `name`, `mode`, and `closed` attributes of the file object and print
their values.
Finally, we attempt to access the `encoding` attribute, which is only available if the file is
opened in text mode. If the file is not opened in text mode, attempting to access the
`encoding` attribute will result in an error.
By using these file object attributes, you can access and manipulate various properties of
files in your Python programs.
Example:
# Create a text file
f=open("f:\\file1.txt","w")
print("file created")
f.write("Python")
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 12 of 34
f.write("Java")
f.write("Oracle")
f.write("C#.Net")
f.write("65")
f.close()
Output:
file created
print() function
Example:
# Create a student file to store rollno,name,s1,s2
f=open("f:\\marks.txt","a")
while True:
rno=int(input("Rollno "))
name=input("Name ")
s1=int(input("Subject1 Marks "))
s2=int(input("Subject2 Marks "))
print(rno,name,s1,s2,file=f)
ch=input("Add another student?")
if ch=="no":
f.close()
break
Output:
Rollno 1
Name naresh
Subject1 Marks 60
Subject2 Marks 70
Add another student?yes
Rollno 2
Name suresh
Subject1 Marks 30
Subject2 Marks 40
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 13 of 34
Add another student?yes
Rollno 3
Name kishore
Subject1 Marks 60
Subject2 Marks 70
Add another student?yes
Rollno 4
Name ramesh
Subject1 Marks 80
Subject2 Marks 70
Add another student?yes
Rollno 5
Name rajesh
Subject1 Marks 99
Subject2 Marks 90
Add another student?no
read(size=- 1)
Read and return at most size characters from the stream as a single str. If size is negative
or None, reads until EOF (End Of File).
readline(size=- 1)
Read until newline or EOF and return a single str. If the stream is already at EOF, an empty
string is returned.
If size is specified, at most size characters will be read.
Example:
# Program to read content of file1.txt
f=open("f:\\file1.txt","r")
s=f.read()
print(s)
f.close()
f1=open("f:\\file1.txt","r")
s1=f1.read(2)
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 14 of 34
print(s1)
s2=f1.read(3)
print(s2)
s3=f1.read(2)
print(s3)
s4=f1.read(1)
print(s4)
f1.close()
Output:
PythonJavaOracleC#.Net65
Py
tho
nJ
a
Example:
# Program to read content of marks.txt
f=open("f:\\marks.txt","r")
while True:
stud=f.readline()
if stud==' ':
break
print(stud,end='')
f.close()
Output:
101 Naresh 60 70
102 Suresh 50 80
103 Rajesh 40 50
104 Kishore 30 40
1 naresh 60 70
2 suresh 30 40
3 kishore 60 70
4 ramesh 80 70
5 rajesh 99 90
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 15 of 34
Example:
# Read content from marks.txt
f=open("f:\\marks.txt","r")
while True:
stud=f.readline()
if stud=='':
break
list1=stud.split()
tot=int(list1[2])+int(list1[3])
avg=tot/2
result="pass" if int(list1[2])>=40 and int(list1[3])>=40 else "fail"
print(f'{list1[0]}\t{list1[1]}\t{list1[2]}\t{list1[3]}\t{tot}\t{avg:.2f}\t{result}')
Output:
101 Naresh 60 70 130 65.00 pass
102 Suresh 50 80 130 65.00 pass
103 Rajesh 40 50 90 45.00 pass
104 Kishore 30 40 70 35.00 fail
1 naresh 60 70 130 65.00 pass
2 suresh 30 40 70 35.00 fail
3 kishore 60 70 130 65.00 pass
4 ramesh 80 70 150 75.00 pass
5 rajesh 99 90 189 94.50 pass
Example:
# Write a program to copy content of one file to another file
s=f1.read()
f2.write(s)
f1.close()
f2.close()
print("File Copied")
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 16 of 34
Output:
Enter File1 f:\\marks.txt
Enter File2 f:\\marks1.txt
File Copied
The csv module’s reader and writer objects read and write sequences. Programmers can
also read and write data in dictionary form using the DictReader and DictWriter classes.
csv.writer(csvfile)
Return a writer object responsible for converting the user’s data into delimited strings on the
given file-like object
Example:
# Creating csv file
import csv
f=open("f:\\emp.csv","w",newline='')
csvwr=csv.writer(f)
while True:
empno=int(input("EmployeeNo :"))
ename=input("EmployeeName :")
sal=float(input("Employee Salary :"))
csvwr.writerow([empno,ename,sal])
ch=input("Add another employee?")
if ch=="no":
f.close()
break
Output:
EmployeeNo :1
EmployeeName :naresh
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 17 of 34
Employee Salary :40000
Add another employee?yes
EmployeeNo :2
EmployeeName :suresh
Employee Salary :56000
Add another employee?yes
EmployeeNo :3
EmployeeName :kishore
Employee Salary :75000
Add another employee?no
writerow() method of write object convert list/sequence into comma separated values
string. This string is written side file using file object.
csv.reader(csvfile)
Return a reader object which will iterate over lines in the given csvfile. csvfile can be any
object which supports the iterator protocol and returns a string each time
its __next__() method is called.
Binary File
In binary file data is represented in byte format (OR) binary file is collection of bytes. It allows
reading and writing only bytes data.
In order to work with binary files, the file must be opened in binary mode.
open(“file-name”,”wb”)
open(“file-name”,”rb”)
open(“file-name”,”w”)
Example:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 18 of 34
f=open("f:\\file1.dat","wb")
f.write("Hello".encode())
b1=bytes(10)
f.write(b1)
b2=bytes(range(65,70))
f.write(b2)
f.close()
Output:
Example:
f1=open(image_file1,"rb")
f2=open(image_file2,"wb")
data=f1.read()
f2.write(data)
print("Image is copied..")
f1.close()
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 19 of 34
f2.close()
Output:
Image is copied..
--------------------------------------------------------------------------------------------------------------------------------
Python Command Line Arguments
❖ Python Command line arguments are input arguments(parameters) passed to the
python program(script) when executing them.
❖ Command line arguments are arguments which are given after name of the
program from command shell of operating system is called “Command line
arguments”
In sys module there is a built-in variable / attribute called argv ➔ command line arguments ➔ data
type of this variable is list.
OUTPUT:
C:\Users\Sreenivasu\Desktop>cmdargs0.py # using command prompt
<class 'list'>
length of command line arguments: 1
The command line arguments are:
The above figure is showing python program named as cmdargs0.py can be executed
from system command prompt.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 21 of 34
Figure shows on desktop we have a python program(file) named as ‘cmdargs0’ which is
saved with an extension .py
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 23 of 34
# python program to get length of command line arguments
import sys
arguments = sys.argv[1:] # reading command line arguments excluding python program(script) name
# arguments = sys.argv[1:] #data type of variable argv is list. Hence to read elements in a
list we are using slicing
OUTPUT:
C:\Users\Sreenivasu>cd desktop
C:\Users\Sreenivasu\Desktop>cmdargs1.py
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 24 of 34
0
Number of command line arguments: []
C:\Users\Sreenivasu\Desktop>cmdargs1.py 20 25 46 80 90
5
Number of command line arguments: ['20', '25', '46', '80', '90']
Note: screen shots included here for your better understanding of command line
arguments.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 25 of 34
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 26 of 34
Name of the python program is ‘cmdargs2.py’
from sys import argv #from sys module import built-in variable called argv
print("type of argv: ",type(argv))
print("the length of variable 'argv' in sys module:",len(argv))
for x in argv:
print(x)
OUTPUT:
C:\Users\Sreenivasu>cd desktop
C:\Users\Sreenivasu\Desktop>cmdargs2.py
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 27 of 34
type of argv: <class 'list'>
the length of variable 'argv' in sys module: 1
C:\Users\Sreenivasu\Desktop\cmdargs2.py
C:\Users\Sreenivasu\Desktop>cmdargs2.py 10 20 30 40 50
type of argv: <class 'list'>
the length of variable 'argv' in sys module: 6
C:\Users\Sreenivasu\Desktop\cmdargs2.py
10
20
30
40
50
#write a python program with command line argument to count the length of
the arguments
import sys
OUTPUT:
C:\Users\Sreenivasu>cd desktop
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 28 of 34
C:\Users\Sreenivasu\Desktop>cmdargs3.py #from system command prompt
Note: In command line arguments name of python program is also one element in ‘argv’
variable which is a list.
Steps:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 29 of 34
Note we have saved our python program on desktop with the name ‘cmdargs3.py’
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 30 of 34
#Write a python program to Sum up all Given inputs using command line
arguments.
OUTPUT:
C:\Users\Sreenivasu\Desktop>cmdargs4.py
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 31 of 34
sum of arguments is: 0
C:\Users\Sreenivasu\Desktop>cmdargs4.py 10 25 45 50
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>
Traceback (most recent call last):
File "C:\Users\Sreenivasu\Desktop\cmdargs4.py", line 8, in <module>
sum=sum+x
~~~^~
TypeError: unsupported operand type(s) for +: 'int' and 'str'
#Write a python program to Sum up all Given inputs using command line
arguments.
#note=> every argument passed to python program from command prompt is a string
#hence type conversion is required string object must be converted into int object.
OUTPUT:
C:\Users\Sreenivasu\Desktop>cmdargs4.py 10 20 35 40
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>
sum of arguments is: 105
#Write a python program to Sum up all Given inputs using command line arguments.
#note=> every argument passed to python program from command prompt is a string
#hence type conversion is required
OUTPUT:
C:\Users\Sreenivasu\Desktop>cmdargs4.py 1 2 3 4 50 60
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>
sum of arguments is: 120
length of command line arguments: 7
KEYNOTE:
Python sys module has variable called ‘argv’ stores the command line arguments into a list, we can
access it using sys.argv.
This is very useful and simple way to read command line arguments as String.
C:\Users\Sreenivasu\Desktop>cmdargs4.py 1 2 3 4 50 60
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>
sum of arguments is: 120
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 33 of 34
length of command line arguments: 7
Remember & observe the output in above program number of arguments which passed
to python program(script) from command prompt is 6 only. But if you look at the output
length of command line arguments is : 7 which means in argv list python program(script
name) is also one command line argument which is present in argv list in index position 0.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 34 of 34