Lecture7_py
Lecture7_py
e
WHICH WE PERFORM ON THE FILES
g
Python can be used to perform operations on a file. (read & write data)
olle
a C
Types of all files
n
p
FILES SAVED IN THE FORM OF THE CHARACTERS
A
1. Text Files : .txt, .docx, .log etc.
BOTH TYPES OF THE FILES ARE SAVED IN THE
FORM OF 1 AND 0 IN THE COMPUTER
2. Binary Files : .mp4, .mov, .png, .jpeg etc.
ge
We have to open a file before reading or writing.
olle
WHEN WE NOT GIVE THE MODE TO THE
C
PYTHON ITS ASSUME THAT WE READ THE
f = open( “file_name”, “mode”) FILE(BY DEFAULT)
pna
A
sample.txt r : read mode
demo.docx w : write mode
data = f.read( )
f.close( )
WHEN WE USED THE "w" ALL DATA DELETE THEN WE CAN WRITE WITH
START
lege
Col
a
R+= MEANS READING AND WRITING BOTH WITHOUT TRUNCATING( BUT ITS TRUNCATE AT THE EXISTING VALUE)
n
POINTER POSITION IS AT THE START
p
W+= MEANS READING AND WRITING BOTH WITH TRUNCATING AND THERE IS NO POINTER POSITION DUE TO
A
THE TRUNCATION
A+= MEANS READING AND APPENDING,POINTER POSITION IS AT THE END WITHOUT THE TRUNCATING
IN THE READING(PRINTING) OF A FILE THERE IS A
/n AFTER THE COMPLITION OF ONE LINE, THEREFORE
ITS SKIP ONE LINE AFTER THE COMPLITION.
Reading a file
e
WHEN WE WRITE A NUMBER IN THE () BRACKETS
g
ONLY GIVEN NUMBERS OF CHARACTERS ARE PRINTED
e
(READ)
ll
data = f.read( ) #reads entire file
Co
WHEN WE READ THE DATA ONCE AND COMPLETE
a
READLINE FUNCTION PRINT THE EMPTY LINES
pn
data = f.readline( ) #reads one line at a time
A
FOR EXAMPLE:
WE CAN PRINT(READ) THE COMPLETE LINE
WITH THIS FUNCTION OF READING
Writing to a file
lege
l
f = open( “demo.txt”, “w”)
a Co
f.write( “this is a new line“ ) #overwrites the entire file
lege
l
with open( “demo.txt”, “a”) as f:
Co
data = f.read( )
pna
A
Deleting a File
ge
using the os module
olle
Module (like a code library) is a file written by another programmer that generally has
C
a functions we can use.
pna
A
import os
os.remove( filename )
Let‘s Practice
ge
Create a new file “practice.txt” using python. Add the following data in it:
olle
C
Hi everyone
na
we are learning File I/O
Ap
using Java.
I like programming in Java.
WAF that replace all occurrences of “java” with “python” in above file.
ege
WAF to find in which line of the file does the word “learning”occur first.
l
ol
Print -1 if word not found.
na C
Ap
From a file containing numbers separated by comma, print the count of even numbers.