0% found this document useful (0 votes)
6 views9 pages

Lecture7 Py Invert

The document provides an overview of file I/O operations in Python, including reading and writing to text and binary files. It explains how to open, read, write, and delete files using Python's built-in functions and the os module. Additionally, it includes practice exercises for creating files and manipulating their contents.

Uploaded by

singhdoxic9393
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views9 pages

Lecture7 Py Invert

The document provides an overview of file I/O operations in Python, including reading and writing to text and binary files. It explains how to open, read, write, and delete files using Python's built-in functions and the os module. Additionally, it includes practice exercises for creating files and manipulating their contents.

Uploaded by

singhdoxic9393
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

File I/O in Python

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.

2. Binary Files : .mp4, .mov, .png, .jpeg etc.


Open, read & close File

ge
We have to open a file before reading or writing.

olle
C
f = open( “file_name”, “mode”)

pna
A
[Link] r : read mode
[Link] w : write mode

data = [Link]( )

[Link]( )
lege
Col
pna
A
Reading a file

lege
l
data = [Link]( ) #reads entire file

a Co
pn
data = [Link]( ) #reads one line at a time

A
Writing to a file

lege
l
f = open( “[Link]”, “w”)

a Co
[Link]( “this is a new line“ ) #overwrites the entire file

Apn
f = open( “[Link]”, “a”)

[Link]( “this is a new line“ ) #adds to the file


with Syntax

lege
l
with open( “[Link]”, “a”) as f:

Co
data = [Link]( )

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
[Link]( filename )
Let‘s Practice

ge
Create a new file “[Link]” 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.

Search if the word “learning” exists in the file or not.


Let‘s Practice

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.

You might also like