Unit-4 PPTs
Unit-4 PPTs
SK Classes …. (Sanjeev
Kr. Kapoor, AP, KIET Group of Institutions)
Sieve of Eratosthenes
SK Classes …. (Sanjeev
Kr. Kapoor, AP, KIET Group of Institutions)
Final Solution in Yellow
SK Classes …. (Sanjeev
Kr. Kapoor, AP, KIET Group of Institutions)
Try the solution
SK Classes …. (Sanjeev
Kr. Kapoor, AP, KIET Group of Institutions)
File Manipulation in python
• 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
• You can use a file to store data permanently
SK Classes …. (Sanjeev
Kr. Kapoor, AP, KIET Group of Institutions)
Working of open() function
• We use open () function in Python to open a file in read or write mode. As explained above,
open ( ) will return a file object.
• The syntax being:
file_variable= open(filename, mode).
There are three kinds of mode, that Python provides and how files can be opened:
• “ r “, for reading.
• “ w “, for writing.
• “ a “, for appending.
• “ x “, creates specified file returns error if file already exist.
• The default is reading in text mode. In this mode, we get strings when reading from the file.
example
• file = open('geek.txt', 'r')
• # This will print every line one by one in the file
• for each in file:
• print (each)
Creating a file
• sales_file = open('sales.txt', 'w')
Example—
f = open("demofile.txt", "a")
f.write("This line is added at the end by write command")
f = open("demofile.txt", "r")
print(f.read( ))
f.close( )
f = open("demofile.txt", "w")
f.write("Sorry! the contents are deleted")
Delete a File
To delete a file, we must import the OS module, and run its os.remove() function:
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
• Check if File exist:
• To avoid getting an error, we might want to check if the file exists before we try to delete it:
• Example
• Syntax is
• f = open("demofile.txt", "r")
• print(f.readlines( ))
• OUTPUT—
•
• ['Hello World!\n', 'This file is only for testing purpose.\n', 'File handling in Python.\n', 'All the
Best!!!’]
• (File content as list of lines)
• NOTE:
• 1. After performing any operations, we must close the file.
• f.close( )
• 2. By looping through the lines of the file, we can read the whole file, line by line:
• f = open("demofile.txt", "r")
for lines in f:
print(lines)
F.seek, F.tell
• seek() used to change the position of file handler/pointer to given
position.
Sytax: f.seek(offset)
For text mode files.
• f.tell() gives the current location of file pointer.