Lecture7 Py
Lecture7 Py
ge
Python can be used to perform operations on a file. (read & write data)
olle
a C
Types of all files
n
Ap
1. Text Files : .txt, .docx, .log etc.
ge
We have to open a file before reading or writing.
olle
C
f = open( “file_name”, “mode”)
pna
A
sample.txt r : read mode
demo.docx w : write mode
data = f.read( )
f.close( )
lege
Col
pna
A
Reading a file
lege
l
data = f.read( ) #reads entire file
a Co
pn
data = f.readline( ) #reads one line at a time
A
Writing to a file
lege
l
f = open( “demo.txt”, “w”)
a Co
f.write( “this is a new line“ ) #overwrites the entire file
Apn
f = open( “demo.txt”, “a”)
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.