Unit 4
Unit 4
Unit 4
Types of files:
• Like C, Python also supports two types of files: text files and binary files.
• Contents of a binary file are not human readable. If you want that data stored in the file
must be human readable then store the data in a text file.
• In a text file, each line of data ends with a newline character i.e \n. Each file ends with
a special character called the end-of-file (EOF) marker. Each line in a text file can have
maximum of 255 characters.
••
•
Python File Handling
➢ Python too supports file handling and allows users to handle files i.e., to
read and write files, along with many other file handling options, to
operate on files.
➢ Python treats files differently as text or binary and this is important. Each
line of code includes a sequence of characters and they form a text file.
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.
Syntax
5 Opens a file for writing only. Overwrites the file if the file
exists. If the file does not exist, creates a new file for
writing.
b
6
Opens the file in binary mode
t
7
Opens the file in text mode (default)
+
8
open file for updating (reading and writing)
wb
Opens a file for writing only in binary format. Overwrites
9
the file if the file exists. If the file does not exist, creates
a new file for writing.
w+
Opens a file for both writing and reading. Overwrites the
10
existing file if the file exists. If the file does not exist,
creates a new file for reading and writing.
wb+
Opens a file for both writing and reading in binary
11 format. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and
writing.
a
Opens a file for appending. The file pointer is at the end
12 of the file if the file exists. That is, the file is in the
append mode. If the file does not exist, it creates a new
file for writing.
ab
Opens a file for appending in binary format. The file
pointer is at the end of the file if the file exists. That is,
13 the file is in the append mode. If the file does not exist,
it creates a new file for writing.
a+
Opens a file for both appending and reading. The file
14 pointer is at the end of the file if the file exists. The file
opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
ab+
Opens a file for both appending and reading in binary
15 format. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does
not exist, it creates a new file for reading and writing.
x
16 open for exclusive creation, failing if the file already
exists
Explain different file object attribute with example.
Exapmle:
Syntax
1. fileobject.close()
After closing the file, we cannot perform any operation in the file. The file needs to be
properly closed. If any exception occurs while performing some operations in the file
then the program terminates without closing the file.
1. try:
2. fileptr = open("file.txt")
3. # perform file operations
4. finally:
5. fileptr.close()
NOTE: Once the file is closed using the close() method, any attempt to
use the file object will result in an error.
The syntax to open a file using with the statement is given below.
The advantage of using with statement is that it provides the guarantee to close the
file regardless of how the nested block exits.
It is always suggestible to use the with statement in the case of files because, if the
break, return, or exception occurs in the nested block of code then it automatically
closes the file, we don't need to write the close() function. It doesn't let the file to
corrupt.
Example
1. with open("file.txt",'r') as f:
2. content = f.read();
3. print(content)
Syntax:
1. 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.
Example
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r")
3. #stores all the data of the file into the variable content
4. content = fileptr.read(10)
5. # prints the type of the data stored in the file
6. print(type(content))
7. #prints the content of the file
8. print(content)
9. #closes the opened file
10. fileptr.close()
Output:
<class 'str'>
Python is
In the above code, we have read the content of file2.txt by using the read() function.
We have passed count value as ten which means it will read the first ten characters
from the file.
If we use the following line, then it will print all content of the file.
1. content = fileptr.read()
2. print(content)
Output:
1. #open the file.txt in read mode. causes an error if no such file exists.
2. fileptr = open("file2.txt","r");
3. #running a for loop
4. for i in fileptr:
5. print(i) # i contains each line of the file
Output:
Consider the following example which contains a function readline() that reads the
first line of our file "file2.txt" containing three lines. Consider the following example.
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r");
3. #stores all the data of the file into the variable content
4. content = fileptr.readline()
5. content1 = fileptr.readline()
6. #prints the content of the file
7. print(content)
8. print(content1)
9. #closes the opened file
10. fileptr.close()
Output:
We called the readline() function two times that's why it read two lines from the file.
Python provides also the readlines() method which is used for the reading lines. It
returns the list of the lines till the end of file(EOF) is reached.
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r");
3.
4. #stores all the data of the file into the variable content
5. content = fileptr.readlines()
6.
7. #prints the content of the file
8. print(content)
9.
10. #closes the opened file
11. fileptr.close()
Output:
writelines() method:
It is used to write a list of strings. Whereas write() method does not accept list,
number type argument only string type argument is accepted.
Example:
f1=open("file3.txt","w")
lines=["hello world","welcome to programmming","enjoy
learning"]
f1.writelines(lines)
f1=open("file3.txt","r")
print(f1.read())
Output:
hello worldwelcome to programmmingenjoy learning
append() method
Once you have stored some data in a file, you can always open file again to write
more data. For appending a data, mode is used “a”. while write() overwrites
existing data to write the new data in the file.
Example:
f=open("deepika.txt","a")
f.write("\nmy name is deepika")
f.close()
f=open("deepika.txt","r")
print(f.read())
Output:
i live in meerut
my name is Deepika
Output:
For this purpose, the Python provides us the seek() method which enables us to modify
the file pointer position externally.
Syntax:
1. <file-ptr>.seek(offset[, from)
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it is
set to 0, the beginning of the file is used as the reference position. If it is set to 1, the
current position of the file pointer is used as the reference position. If it is set to 2, the
end of the file pointer is used as the reference position.
Example 1
Output:
Example 2
Python OS module
Renaming the file
The Python os module enables interaction with the operating system. The os module
provides the functions that are involved in file processing operations like renaming,
deleting, etc. It provides us the rename() method to rename the specified file to a new
name. The syntax to use the rename() method is given below.
Syntax:
1. rename(current-name, new-name)
The first argument is the current file name and the second argument is the modified
name. We can change the file name by passing these two arguments.
Example 1:
1. import os
2.
3. #rename file2.txt to file3.txt
4. os.rename("file2.txt","file3.txt")
Output:
1. remove(file-name)
Example 1
1. import os;
2. #deleting the file named file3.txt
3. os.remove("file3.txt")
Ans:
f=open("deepika.txt","r+")
b=f.read()
print(b)
c=b.split("\n")
print(c)
for i in c:
print(i)
Output:
i live in meerut
my name is deepika
my name is deepika
['i live in meerut', ' my name is deepika', 'my name is deepika']
i live in meerut
my name is deepika
my name is deepika
7. Program that accepts filename as an input from the user. Open the file and count the
number of times a character appears in the file.
8. Program that copies contents of one file into another file in such a way that all
comments lines are skipped and not copied to second file.
with open("first.txt","w") as f:
f.write("# this is the first file\n")
f.write("i am deepika gupta\n")
f.write("i am a teacher")
with open("first.txt","r") as f:
with open("second.txt","w") as f1:
while True:
a=f.readline()
if len(a)!=0:
if a[0]=='#':
continue
else:
f1.write(a)
else:
break
f1=open("first.txt","r")
f2=open("second.txt","w")
while True:
a=f1.readline()
if len(a)!=0:
if a[0]=='#':
continue
else:
f2.write(a)
else:
break
f=open("second.txt","r")
print(f.read())
Output:
i am deepika gupta
i am a teacher
9. Program that reads a file line by line. Each line read from the file is copied to another
file with line numbers specified at the beginning of the line.
f1=open("one.txt","r")
f2=open("second.txt","w")
num=1
for i in f1:
print(i)
f2.write(str(num)+":"+i)
num=num+1
f1.close()
f2.close()
Output:
1:Mango
2:banana
3:Grapes
10. Program to count the number of words in a text file.
Ans:
12. Program to read a string from the user and appends it into a file.
Ans:
13. Program to count the occurrences of a word in a text file
Ans:
14. Python Program to copy the contents of one file into another.
Ans: