Unit 6 notes
Unit 6 notes
Types of Files
There are two types of files.
1. Text File
2. Binary file
Data is present in the form of characters. Data is present in the encoded form.
The plain text is present in the file. The image, audio, or text data can be
present in the file.
It cannot be corrupted easily. Even if single bit is changed then the file
gets corrupted.
It can be opened and read using simple text It cannot read using the text editor like
editor like Notepad Notepad.
It have the extension such as .py or .txt It can have application defined extension.
Opening a File:
In python there is a built in function open() to open a file.
Syntax:
File_object=open(file_name,mode)
Where file_object is used as a handle to the file.
Example:
F=open(“test.txt”)
Here file named test.txt is opened and the file object is in variable F.
We can open the file in text mode or in binary mode. There are various modes of a
file in which it is opened.
Example:
Fo=open(“test.txt”,w) #opens a file in write mode.
Fo=open(“text.txt”,rt) #opens a file for reading in text mode
Write a python program to print the details of the file object.
Fo= open(“test.txt”, “r+”)
print(Fo)
Output:
<_io.TextIOWrapper name='test.txt' mode='rt' encoding='cp1252'>
File object Attributes:
On opening the file successfully, the file object is returned. It is possible to get
different types of information related to file using the attributes associated with the
file object.
These attributes are:
1. fileobj.name: It returns the name of file.
2. fileobj.mode: It returns mode of the file with which the file is opened.
3. fileobj.closed: It returns True if the file is closed otherwise false.
Writing Files
For writing the contents to the file, we must open it in writing mode. Hence we
use ‘w’, or ‘a’, or ‘x’ as a file mode.
The write method is used to write the contents to the file.
Syntax:
File_object.write(contents)
Example:
fo=open(“G:\\text2.txt”, “wt”)
fo.write(“Introduction to file operations”)
fo.close()
Output:
Open text2.txt file and check whether the contents are written or not
The writelines() method:
The writelines() method is used to write list of strings to the file.
Example:
fo=open("G:\\text3.txt","wt")
lines=["Welcome to the python programming\n","It is fun\n","Python is
easy\n","But it is powerful programming language."]
fo.writelines(lines)
fo.close()
Output:
Open the file text3.txt, it will display above lines.
Write a python program to write n number of lines to the file and display all
these lines as output.
print("How many lines you want to write:")
n=int(input())
outfile=open("G:\\text4.txt","wt")
for i in range(n):
print("Enter the line:")
line=input()
outfile.write("\n"+line)
outfile.close()
print("The contents of the files are ...")
infile=open("G:\\text4.txt","rt")
print(infile.read())
infile.close()
Output:
How many lines you want to write:
3
Enter the line:
This is first line
Enter the line:
This is the second line
Enter the line:
This is third line
The contents of the files are ...
This is first line
This is the second line
This is third line
Write a python program to write the contents in ‘one.txt’ file. Read these
contents and write them to another file named ‘two.txt’.
print("How many lines you want to write:")
n=int(input())
outfile=open("G:\\one.txt","wt")
for i in range(n):
print("Enter the line:")
line=input()
outfile.write("\n"+line)
outfile.close()
infile=open("G:\\one.txt","rt")
outfile=open("G:\\two.txt","wt")
i=0
for i in range(n+1):
line=infile.readline()
outfile.write("\n"+line)
infile.close()
outfile.close()
print("The contents of the files are ...")
infile=open("G:\\two.txt","rt")
print(infile.read())
infile.close()
Output:
How many lines you want to write:
3
Enter the line:
This is first line
Enter the line:
This is second line
Enter the line:
This is third line
The contents of the files are...
This is first line
This is second line
This is third line
File Positions:
Two methods are:
1.seek() Method: It is used to change the file position. It sets the file’s current
position at the offset.
Syntax:
Fileobject.seek(offset[,whence])
Where,
offset: This is the position of the read/write pointer within the file.
whence: This is optional and defaults to 0 which means absolute file positioning,
other values are 1 which means seek relative to the current positions and 2 means seek
relative to the file’s end.
2.tell() Method: The method tell() returns the current position of the file read/write
pointer within the file.
Syntax:
Fileobject.tell()
Example:
inf=open("G:\\text3.txt","rt")
print("\tThe Contents of the files are:")
print(inf.read())
print("\tThe current position is:")
print(inf.tell())#get current position of file
inf.seek(0)#moves the file cursor to the initial position.
print("\tThe current Position is:")
print(inf.tell())#get current position of file
inf.seek(20)
print("\tThe current Position is:")
print(inf.tell())#get current position of file
print("\tThe Contents of the files are:")
print(inf.read())
Output:
The Contents of the files are:
Welcome to the python programming
It is fun
Python is easy
But it is powerful programming language.
Python has a wide scope in future.
The current position is:
140
The current Position is:
0
The current Position is:
20
The Contents of the files are:
n programming
It is fun
Python is easy
But it is powerful programming language.
Python has a wide scope in future.
Directory Methods:
1) Getting current working directory: We use function named getcwd(), which returns
the name of current working directory.
Example:
import os
print(os.getcwd())
Output:
C:\Users\Ganesh\AppData\Local\Programs\Python\Python37-32
2) Displaying all the files and sub-directories inside a directory: We use function
named listdir(), which returns contents of directory.
Example:
import os
print(os.listdir())
Output:
['aa.py', 'add.py', 'assignment_10.py', 'assignment_11.py', 'assignment_12.py',
'assignment_2.py', 'assignment_3.py', 'assignment_4.py', 'assignment_5.py',
'assignment_6.py', 'assignment_7.py', 'assignment_8.py‘]
3) Creating a new Directory:
We can create a new directory using mkdir() method.
Example:
import os
os.mkdir("Mypythonprograms")#create a folder named mypythonprograms
print(os.listdir())#displaying the directory contents
4) Removing the directory or a file:
A file can be deleted using remove() method.
The rmdir() method remove an empty directory.
Example:
import os
os.remove("a1.py")#remove files test1.txt
print(os.listdir())#display the directory contents
os.rmdir("Mypythonprograms")#removes the directory named Mypythonprograms
print(os.listdir())#displays the directory contents
Dictionary Methods:
1. Adding item to dictionary: we can add the item to the dictionary.
>>> a={1:'red',2:'blue',3:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow'}
>>> a[4]='black'
>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow', 4: 'black'}
2. Remove item from dictionary: For removing an item from the dictionary we use
the keyword del.
>>> a={1: 'red', 2: 'blue', 3: 'yellow', 4: 'black'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow', 4: 'black'}
>>> del a[2]
>>> print(a)
{1: 'red', 3: 'yellow', 4: 'black'}
3) Updating the value of the dictionary: we can update the value of the dictionary by
directly assigning the value to corresponding key position.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
>>> a[2]='pink'
>>> print(a)
{1: 'red', 2: 'pink', 3: 'black', 4: 'yellow'}
4) Checking length: The len() function gives the number of pairs in the dictionary.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> len(a)
4