SlideShare a Scribd company logo
LEARNING OBJECTIVES
At the end of this chapter you will be able to learn :
❏ Understanding Files
❏ Types of Files
❏ Understanding Text Files
❏ Opening and closing Text files
❏ Reading and writing in Files
❏ Understanding Binary Files
❏ Pickling and Unpickling
❏ Opening and closing Binary files
❏ Reading and writing in Binary Files
❏ CSV (Comma separated values) files. 2
NEED FOR DATA FILE HANDLING
● Mostly, in programming languages, all the values or data are stored in some
variables which are volatile in nature.
● Because data will be stored into those variables during run-time only and will be
lost once the program execution is completed. Hence it is better to save these data
permanently using files.
3
INTRODUCTION
● A file in itself is a sequence of bytes stored in some storage device like hard-disk,
pen-drive etc.
● Python allow us to create and manage three types of files :
1. TEXT FILE
2. BINARY FILE
3. CSV (Comma Separated Values) FILES
4
TEXT FILE
● A text file is structured as a sequence of lines.
● Line is a sequence of characters (ASCII or UNICODE)
● Stores information in ASCII or Unicode characters.
● Each line of text is terminated by a special character known as End Of Line
character.
● Text files are stored in human readable form and they can also be created using
any text editor.
5
BINARY FILE
● A file that contains information in the same format in which information
is held in memory.
● Binary file contains arbitrary binary data.
● So when we work on binary file, we have to interpret the raw bit
pattern(s) read from the file into correct type of data in our program.
● Python provides special module(s) for encoding and decoding of data
for binary file.
6
CSV FILES
● CSV stands for Comma Separated Values.
● CSV is just like a text file, in a human readable format which is extensively
used to store tabular data, in a spreadsheet or database.
● The separator character of CSV files is called a delimiter.
● Default delimiter is comma (,). Other delimiters are tab (t), colon (:), pipe (|),
semicolon (;) characters.
7
8
STEPS TO PROCESS A FILE
1. Determine the type of file usage.
a. Reading purpose : If the data is to be brought in from a file to memory
b. Writing purpose : If the data is to be sent from memory to file.
2. Open the file and assign its reference to a file object or file-handle.
3. Process the file as required : Perform the desired operation from the file.
4. Close the file.
9
OPENING A TEXT FILE
● The key function for working with files in Python is the open() function.
● It accepts two parameters : filename, and mode.
Syntax:
<file_object_name> = open(<file_name>,<mode>)
Example: f = open(“demo.txt”,”r”)
● Can specify if the file should be handled as binary or text Mode :
○ "t" - Text - Default value. Text mode
○ "b" - Binary - Binary mode (e.g. images)
10
● File Objects:
○ It serves as a link to file residing in your computer.
○ It is a reference to the file on the disk and it is through this link python
program can perform operations on the files.
● File access modes:
○ It governs the type of operations(such as read or write or append)
possible in the opened file.
11
● Various Modes for opening a text file are:
Mode Description
“r” Read Default value. Opens a file for reading, error if the file does
not exist.
“w” Write Opens a file for writing, creates the file if it does not exist
“a” Append Opens a file for appending, creates the file if it does not exist
“r+” Read and
Write
File must exist otherwise error is raised.Both reading and
writing operations can take place.
“w+” Write and
Read
File is created if it does not exist.If the file exists past data is
lost (truncated).Both reading and writing operations can
take place.
“a+” Append and
Read
File is created if it does not exist.If the file exists past data is
not lost .Both reading and writing(appending) operations
can take place.
12
CLOSING A FILE
● close()- method will free up all the system resources used by the file, this means
that once file is closed, we will not be able to use the file object any more.
● <fileobject>. close() will be used to close the file object, once we have finished
working on it.
Syntax:
<fileObject>.close()
Example : f.close()
● It is important to close your files, as in some cases, due to buffering,changes
made to a file may not show until you close the file.
13
READING FROM A FILE
➔ A Program reads a text/binary file from hard disk. Here File acts like an input
to the program.
➔ Followings are the methods to read a data from the file:
◆ read() METHOD
◆ readline() METHOD
◆ readlines() METHOD
14
read() METHOD
● By default the read() method returns the whole text, but you can also specify
how many characters you want to return by passing the size as argument.
Syntax: <file_object>.read([n])
where n is the size
● To read entire file : <file_object>.read()
● To reads only a part of the File : <file_object>.read(size)
f = open("demo.txt", "r")
print(f.read(15))
Returns the 15 first characters of the file "demo.txt". 15
16
readline() METHOD
● readline() will return a line read, as a string from the file.
Syntax:
<file_object>.readline()
● Example
f = open("demo.txt", "r")
print(f.readline())
● This example program will return the first line in the file “demo.txt”
irrespective of number of lines in the text file. 17
Reading a complete file line by line using readline().
18
readlines() METHOD
● readlines() method will return a list of strings, each separated by n
● readlines() can be used to read the entire content of the file.
.
Syntax:
<file_object>.readlines()
● It returns a list, which can then be used for manipulation.
Example : f = open("demofile.txt", "r")
print(f.readlines())
19
Read a file using Readlines()
20
21
WRITING TO A TEXT FILE
● A Program writes into a text/binary file in hard disk.
● Followings are the methods to write a data to the file.
○ write () METHOD
○ writelines() METHOD
● To write to an existing file, you must add a parameter to the open()
Function which specifies the mode :
○ "a" - Append - will append to the end of the file
○ "w" - Write - will overwrite any existing content
22
write() Method
● write() method takes a string ( as parameter ) and writes it in the file.
● For storing data with end of line character, you will have to add n character to end
of the string
● Example:
Open the file "demo_append.txt" and append content to the file:
f = open("demo_write.txt", ""a)
f.write("Hello students n We are learning data file handling…..!")
f.close()
f = open("demo_write.txt", "r") #open and read the file after the appending
print(f.read()) 23
24
writelines() METHOD
● For writing a string at a time, we use write() method, it can't be used
for writing a list, tuple etc. into a file.
● Python file method writelines() writes a sequence of strings to the file.
The sequence can be any iterable object producing strings, typically a
list of strings.
● So, whenever we have to write a sequence of string, we will use
writelines(), instead of write().
25
26
The flush()
The flush function forces the writing of data on disc still pending on the
output buffer.
Syntax : <file_object>.flush()
27
28
Standard Input, Output, and Error
Streams
❏ Keyboard is the standard input device
❏ stdin - reads from the keyboard
❏ Monitor is the standard output device.
❏ stdout - prints to the display
❏ If any error occurs it is also displayed on the monitor and hence it is
also the standard error device.
❏ Same as stdout but normally only for errors (stderr)
The standard devices are implemented as files called streams. They can be
used by importing the sys module.
29
DATA FILE HANDLING IN BINARY
FILES
● Files that store objects as some byte stream are called binary files.
● That is, all the binary files are encoded in binary format , as a sequence of
bytes, which is understood by a computer or machine.
● In binary files, there is no delimiter to end the line.
● Since they are directly in the form of binary, there is no need to translate
them.
● But they are not in human readable form and hence difficult to
understand.
30
● Objects have a specific structure which must be maintained while storing or
accessing them.
● Python provides a special module called pickle module for this.
● PICKLING refers to the process of converting the structure to a byte
stream before writing to a file.
● UNPICKLING is used to convert the byte stream back to the original
structure while reading the contents of the file.
31
Pickling and Unpickling
32
PICKLE Module
● Before reading or writing to a file, we have to import the pickle
module.
import pickle
● It provides two main methods :
○ dump() method
○ load() method
33
Opening and closing binary files
Opening a binary file:
Similar to text file except that it should be opened in binary
mode.Adding a ‘b’ to the text file mode makes it binary - file mode.
EXAMPLE :
f = open(“demo.dat”,”rb”)
Closing a binary file
f.close()
34
● Various Modes for opening a binary file are:
Mode Description
“rb” Read Default value. Opens a file for reading, error if the file does not
exist.
“wb” Write Opens a file for writing, creates the file if it does not exist
“ab” Append Opens a file for appending, creates the file if it does not exist
“r+b”or
“rb+”
Read and
Write
File must exist otherwise error is raised.Both reading and
writing operations can take place.
“w+b”or
“wb+”
Write and
Read
File is created if it does not exist.If the file exists past data is
lost (truncated).Both reading and writing operations can take
place.
“a+b” or
“ab+”
Append and
Read
File is created if it does not exist.If the file exists past data is
not lost .Both reading and writing operations can take place.
35
pickle.dump() Method
● pickle.dump() method is used to write the object in file which is
opened in binary access mode.
Syntax :
pickle.dump(<structure>,<FileObject>)
● Structure can be any sequence in Python such as list, dictionary etc.
● FileObject is the file handle of file in which we have to write.
36
binary_file.dat file
after execution of
the program.
37
pickle.load() Method
● pickle.load() method is used to read data from a file
Syntax :
<structure> = pickle.load(<FileObject>)
● Structure can be any sequence in Python such as list, dictionary etc.
● FileObject is the file handle of file in which we have to write.
38
39
Write a method to write employee
details into a binary file. Take the
input from the user.
Employee Details:
Employee Name
Employee Number
Department
Salary
40
Random Access in Files : tell() and seek()
❏ tell() function is used to obtain the current position of the file pointer
Syntax : f.tell()
❏ File pointer is like a cursor, which determines from where data has to be
read or written in the file.
❏ seek () function is used to change the position of the file pointer to a given
position.
Syntax : f.seek(offset,reference_point)
Where f is the file object
41
CSV files
● CSV stands for Comma Separated Values.It is a type of plain text file that
uses specific structuring to arrange tabular data such as a spreadsheet or
database.
● CSV like a text file , is in a human readable format and extensively used to
store tabular data, in a spreadsheet or database.
● Each line of the file is a data record.
● Each record consists of one or more fields, separated by commas.
● The separator character of CSV files is called a delimiter.
● Default delimiter is (,).
● Other delimiters are tab(t), colon (:), pipe(|), semicolon (;) characters.
42
Python CSV Module
● CSV module provides two types of objects :
○ reader : to read from cvs files
○ writer : to write into csv files.
● To import csv module in our program , we use the following statement:
import csv
43
Opening / Closing a CSV File
● Open a CSV File :
f = open(“demo_csv.csv”,”r”)
OR
f = open(“demo_csv.csv”,”w”)
● Close a CSV File:
f.close()
44
Role of argument newline in opening
of csv files :
● newline argument specifies how would python handle new line characters
while working with csv files on different Operating System.
● Additional optional argument as newline = “”(null string) with the file
open() will ensure that no translation of EOL character takes place.
45
Steps to write data to a csv file
1. Import csv module
import csv
1. Open csv file in write mode.
f = open(“csv_demo.csv”,”w”)
1. Create the writer object.
demo_writer = csv.writer(f)
1. Write data using the methods writerow() or writerows()
demo_writer.writerow(<iterable_object>)
1. Close the file
f.close() 46
Writing in CSV Files
● csv.writer() :
Returns a writer object which writes data into csv files.
● writerow() :
Writes one row of data onto the writer object.
Syntax : <writer_object>.writerow()
● writerows() :
Writes multiple rows into the writer object
Syntax : <writer_object>.writerow()
47
Writing in CSV Files
● To write data into csv files, writer() function of csv module is used.
● csv.writer():
○ Returns a writer object which writes data into writer object.
● Significance of writer object
○ The csv.writer() returns a writer object that converts the data into a
delimited string.
○ The string can be later converted into csv files using the writerow()
or writerows() method.
48
● <writer_object>.writerow() :
Writes one row of data in to the writer object.
● <writer_object>.writerows()
Writes multiple rows into the writer object.
49
50
Reading from CSV Module
● To read data from csv files, reader function of csv module is used.
● csv.reader() :
Returns a reader object.
It loads data from a csv file into an iterable after parsing delimited data.
51
Steps to read data from a csv file
1. Import csv module
import csv
1. Open csv file in read mode.
f = open(“csv_demo.csv”,”r”)
1. Create the reader object.
demo_reader = csv.reader(f)
1. Fetch data through for loop, row by row.
1. Close the file
f.close() 52
53
QUESTIONS FOR PRACTICE
Write a method in python to read the content from a file “Poem.txt”
and display the same on the screen.
Write a method in python to read the content from a file “Poem.txt”
line by line and display the same on the screen.
Write a method in python to count the number of lines from a text file
which are starting with an alphabet T.
Write a method in Python to count the total number of words in a file
54
Write a method in python to read from a text file “Poem.text” to
find and display the occurrence of the word “Twinkle”
Write a method Bigline() in Python to read lines from a text file
“Poem.txt” and display those lines which are bigger than 50
characters.
Write a method to read data from a file. All the lowercase letter
should be stored in the file “lower.txt” , all upper case characters
get stored inside the file “upper.txt” and other characters stored
inside the file “others.txt”
55
THANK YOU
56
Ad

More Related Content

What's hot (20)

UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
BMS Institute of Technology and Management
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
Megha yadav
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in python
TMARAGATHAM
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
Transaction management DBMS
Transaction  management DBMSTransaction  management DBMS
Transaction management DBMS
Megha Patel
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
M.Zalmai Rahmani
 
Xml schema
Xml schemaXml schema
Xml schema
Prabhakaran V M
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
Praveen M Jigajinni
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
Compare Infobase Limited
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
FUNCTION DEPENDENCY  AND TYPES & EXAMPLEFUNCTION DEPENDENCY  AND TYPES & EXAMPLE
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
Vraj Patel
 
stack & queue
stack & queuestack & queue
stack & queue
manju rani
 
Introduction to XHTML
Introduction to XHTMLIntroduction to XHTML
Introduction to XHTML
Hend Al-Khalifa
 
SQL Views
SQL ViewsSQL Views
SQL Views
baabtra.com - No. 1 supplier of quality freshers
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
Arockia Abins
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
narmadhakin
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
Praveen M Jigajinni
 

Similar to File handling with python class 12th .pdf (20)

File Handling in Python -binary files.pptx
File Handling in Python -binary files.pptxFile Handling in Python -binary files.pptx
File Handling in Python -binary files.pptx
deepa63690
 
file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
RonitVaskar2
 
Binary File.pptx
Binary File.pptxBinary File.pptx
Binary File.pptx
MasterDarsh
 
5-filehandling-2004054567151830 (1).pptx
5-filehandling-2004054567151830 (1).pptx5-filehandling-2004054567151830 (1).pptx
5-filehandling-2004054567151830 (1).pptx
lionsconvent1234
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
4HG19EC010HARSHITHAH
 
01 file handling for class use class pptx
01 file handling for class use class pptx01 file handling for class use class pptx
01 file handling for class use class pptx
PreeTVithule1
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
Hemantha Kulathilake
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programming
Srinivas Narasegouda
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
AmitKaur17
 
Data File Handling in Python Programming
Data File Handling in Python ProgrammingData File Handling in Python Programming
Data File Handling in Python Programming
gurjeetjuneja
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
Kongunadu College of Engineering and Technology
 
UNIT 5 PY.pptx - FILE HANDLING CONCEPTS
UNIT 5 PY.pptx   -  FILE HANDLING CONCEPTSUNIT 5 PY.pptx   -  FILE HANDLING CONCEPTS
UNIT 5 PY.pptx - FILE HANDLING CONCEPTS
drkangurajuphd
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
NiharikaDubey17
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
Ad

More from lionsconvent1234 (19)

‌indian hertitage quiz competiton questions.pptx
‌indian hertitage quiz competiton questions.pptx‌indian hertitage quiz competiton questions.pptx
‌indian hertitage quiz competiton questions.pptx
lionsconvent1234
 
quiz-famouspersonalitiesofindiappt-230316132915-5abbe9c2.pptx
quiz-famouspersonalitiesofindiappt-230316132915-5abbe9c2.pptxquiz-famouspersonalitiesofindiappt-230316132915-5abbe9c2.pptx
quiz-famouspersonalitiesofindiappt-230316132915-5abbe9c2.pptx
lionsconvent1234
 
Function oneshot with python programming .pptx
Function oneshot with python programming .pptxFunction oneshot with python programming .pptx
Function oneshot with python programming .pptx
lionsconvent1234
 
natural vegetation and wildlife 9thstudents study class.pptx
natural vegetation and wildlife 9thstudents study class.pptxnatural vegetation and wildlife 9thstudents study class.pptx
natural vegetation and wildlife 9thstudents study class.pptx
lionsconvent1234
 
globalisation and indian economy ppt.pptx
globalisation and indian economy ppt.pptxglobalisation and indian economy ppt.pptx
globalisation and indian economy ppt.pptx
lionsconvent1234
 
climate ppt 9th class students files for mstudy.pptx
climate ppt 9th class students files for mstudy.pptxclimate ppt 9th class students files for mstudy.pptx
climate ppt 9th class students files for mstudy.pptx
lionsconvent1234
 
food security in india 9th class for students.pptx
food security  in india 9th class for students.pptxfood security  in india 9th class for students.pptx
food security in india 9th class for students.pptx
lionsconvent1234
 
poverty as a challenge 9th class for students.pptx
poverty as a challenge 9th class for students.pptxpoverty as a challenge 9th class for students.pptx
poverty as a challenge 9th class for students.pptx
lionsconvent1234
 
displacing indigenous peoples original ppt.pptx
displacing indigenous peoples original ppt.pptxdisplacing indigenous peoples original ppt.pptx
displacing indigenous peoples original ppt.pptx
lionsconvent1234
 
Electoral Politics 9th hoiw its work in system
Electoral Politics 9th hoiw its work in systemElectoral Politics 9th hoiw its work in system
Electoral Politics 9th hoiw its work in system
lionsconvent1234
 
displacingindigenouspeoples-231206213125-96ec05ca.pdf
displacingindigenouspeoples-231206213125-96ec05ca.pdfdisplacingindigenouspeoples-231206213125-96ec05ca.pdf
displacingindigenouspeoples-231206213125-96ec05ca.pdf
lionsconvent1234
 
changing cultural traditions class 11 th History.pptx
changing cultural traditions class 11 th History.pptxchanging cultural traditions class 11 th History.pptx
changing cultural traditions class 11 th History.pptx
lionsconvent1234
 
Electoral Politics of country India 9th.pptx
Electoral Politics of country India 9th.pptxElectoral Politics of country India 9th.pptx
Electoral Politics of country India 9th.pptx
lionsconvent1234
 
constitutional design of india 1234.pptx
constitutional design of india 1234.pptxconstitutional design of india 1234.pptx
constitutional design of india 1234.pptx
lionsconvent1234
 
themakingofglobalworld-230921074414-f75d93db.pptx
themakingofglobalworld-230921074414-f75d93db.pptxthemakingofglobalworld-230921074414-f75d93db.pptx
themakingofglobalworld-230921074414-f75d93db.pptx
lionsconvent1234
 
Money and credit and banking communication system
Money and credit and banking communication systemMoney and credit and banking communication system
Money and credit and banking communication system
lionsconvent1234
 
Blue Futuristic Technology Presentation.pdf
Blue Futuristic Technology Presentation.pdfBlue Futuristic Technology Presentation.pdf
Blue Futuristic Technology Presentation.pdf
lionsconvent1234
 
Blue Futuristic Technology Presentation.pdf
Blue Futuristic Technology Presentation.pdfBlue Futuristic Technology Presentation.pdf
Blue Futuristic Technology Presentation.pdf
lionsconvent1234
 
Blue Futuristic Technology Presentation.pptx
Blue Futuristic Technology Presentation.pptxBlue Futuristic Technology Presentation.pptx
Blue Futuristic Technology Presentation.pptx
lionsconvent1234
 
‌indian hertitage quiz competiton questions.pptx
‌indian hertitage quiz competiton questions.pptx‌indian hertitage quiz competiton questions.pptx
‌indian hertitage quiz competiton questions.pptx
lionsconvent1234
 
quiz-famouspersonalitiesofindiappt-230316132915-5abbe9c2.pptx
quiz-famouspersonalitiesofindiappt-230316132915-5abbe9c2.pptxquiz-famouspersonalitiesofindiappt-230316132915-5abbe9c2.pptx
quiz-famouspersonalitiesofindiappt-230316132915-5abbe9c2.pptx
lionsconvent1234
 
Function oneshot with python programming .pptx
Function oneshot with python programming .pptxFunction oneshot with python programming .pptx
Function oneshot with python programming .pptx
lionsconvent1234
 
natural vegetation and wildlife 9thstudents study class.pptx
natural vegetation and wildlife 9thstudents study class.pptxnatural vegetation and wildlife 9thstudents study class.pptx
natural vegetation and wildlife 9thstudents study class.pptx
lionsconvent1234
 
globalisation and indian economy ppt.pptx
globalisation and indian economy ppt.pptxglobalisation and indian economy ppt.pptx
globalisation and indian economy ppt.pptx
lionsconvent1234
 
climate ppt 9th class students files for mstudy.pptx
climate ppt 9th class students files for mstudy.pptxclimate ppt 9th class students files for mstudy.pptx
climate ppt 9th class students files for mstudy.pptx
lionsconvent1234
 
food security in india 9th class for students.pptx
food security  in india 9th class for students.pptxfood security  in india 9th class for students.pptx
food security in india 9th class for students.pptx
lionsconvent1234
 
poverty as a challenge 9th class for students.pptx
poverty as a challenge 9th class for students.pptxpoverty as a challenge 9th class for students.pptx
poverty as a challenge 9th class for students.pptx
lionsconvent1234
 
displacing indigenous peoples original ppt.pptx
displacing indigenous peoples original ppt.pptxdisplacing indigenous peoples original ppt.pptx
displacing indigenous peoples original ppt.pptx
lionsconvent1234
 
Electoral Politics 9th hoiw its work in system
Electoral Politics 9th hoiw its work in systemElectoral Politics 9th hoiw its work in system
Electoral Politics 9th hoiw its work in system
lionsconvent1234
 
displacingindigenouspeoples-231206213125-96ec05ca.pdf
displacingindigenouspeoples-231206213125-96ec05ca.pdfdisplacingindigenouspeoples-231206213125-96ec05ca.pdf
displacingindigenouspeoples-231206213125-96ec05ca.pdf
lionsconvent1234
 
changing cultural traditions class 11 th History.pptx
changing cultural traditions class 11 th History.pptxchanging cultural traditions class 11 th History.pptx
changing cultural traditions class 11 th History.pptx
lionsconvent1234
 
Electoral Politics of country India 9th.pptx
Electoral Politics of country India 9th.pptxElectoral Politics of country India 9th.pptx
Electoral Politics of country India 9th.pptx
lionsconvent1234
 
constitutional design of india 1234.pptx
constitutional design of india 1234.pptxconstitutional design of india 1234.pptx
constitutional design of india 1234.pptx
lionsconvent1234
 
themakingofglobalworld-230921074414-f75d93db.pptx
themakingofglobalworld-230921074414-f75d93db.pptxthemakingofglobalworld-230921074414-f75d93db.pptx
themakingofglobalworld-230921074414-f75d93db.pptx
lionsconvent1234
 
Money and credit and banking communication system
Money and credit and banking communication systemMoney and credit and banking communication system
Money and credit and banking communication system
lionsconvent1234
 
Blue Futuristic Technology Presentation.pdf
Blue Futuristic Technology Presentation.pdfBlue Futuristic Technology Presentation.pdf
Blue Futuristic Technology Presentation.pdf
lionsconvent1234
 
Blue Futuristic Technology Presentation.pdf
Blue Futuristic Technology Presentation.pdfBlue Futuristic Technology Presentation.pdf
Blue Futuristic Technology Presentation.pdf
lionsconvent1234
 
Blue Futuristic Technology Presentation.pptx
Blue Futuristic Technology Presentation.pptxBlue Futuristic Technology Presentation.pptx
Blue Futuristic Technology Presentation.pptx
lionsconvent1234
 
Ad

Recently uploaded (20)

How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
National Information Standards Organization (NISO)
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdfAPM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
Association for Project Management
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdfIntroduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
james5028
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdfIntroduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
james5028
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 

File handling with python class 12th .pdf

  • 1. LEARNING OBJECTIVES At the end of this chapter you will be able to learn : ❏ Understanding Files ❏ Types of Files ❏ Understanding Text Files ❏ Opening and closing Text files ❏ Reading and writing in Files ❏ Understanding Binary Files ❏ Pickling and Unpickling ❏ Opening and closing Binary files ❏ Reading and writing in Binary Files ❏ CSV (Comma separated values) files. 2
  • 2. NEED FOR DATA FILE HANDLING ● Mostly, in programming languages, all the values or data are stored in some variables which are volatile in nature. ● Because data will be stored into those variables during run-time only and will be lost once the program execution is completed. Hence it is better to save these data permanently using files. 3
  • 3. INTRODUCTION ● A file in itself is a sequence of bytes stored in some storage device like hard-disk, pen-drive etc. ● Python allow us to create and manage three types of files : 1. TEXT FILE 2. BINARY FILE 3. CSV (Comma Separated Values) FILES 4
  • 4. TEXT FILE ● A text file is structured as a sequence of lines. ● Line is a sequence of characters (ASCII or UNICODE) ● Stores information in ASCII or Unicode characters. ● Each line of text is terminated by a special character known as End Of Line character. ● Text files are stored in human readable form and they can also be created using any text editor. 5
  • 5. BINARY FILE ● A file that contains information in the same format in which information is held in memory. ● Binary file contains arbitrary binary data. ● So when we work on binary file, we have to interpret the raw bit pattern(s) read from the file into correct type of data in our program. ● Python provides special module(s) for encoding and decoding of data for binary file. 6
  • 6. CSV FILES ● CSV stands for Comma Separated Values. ● CSV is just like a text file, in a human readable format which is extensively used to store tabular data, in a spreadsheet or database. ● The separator character of CSV files is called a delimiter. ● Default delimiter is comma (,). Other delimiters are tab (t), colon (:), pipe (|), semicolon (;) characters. 7
  • 7. 8
  • 8. STEPS TO PROCESS A FILE 1. Determine the type of file usage. a. Reading purpose : If the data is to be brought in from a file to memory b. Writing purpose : If the data is to be sent from memory to file. 2. Open the file and assign its reference to a file object or file-handle. 3. Process the file as required : Perform the desired operation from the file. 4. Close the file. 9
  • 9. OPENING A TEXT FILE ● The key function for working with files in Python is the open() function. ● It accepts two parameters : filename, and mode. Syntax: <file_object_name> = open(<file_name>,<mode>) Example: f = open(“demo.txt”,”r”) ● Can specify if the file should be handled as binary or text Mode : ○ "t" - Text - Default value. Text mode ○ "b" - Binary - Binary mode (e.g. images) 10
  • 10. ● File Objects: ○ It serves as a link to file residing in your computer. ○ It is a reference to the file on the disk and it is through this link python program can perform operations on the files. ● File access modes: ○ It governs the type of operations(such as read or write or append) possible in the opened file. 11
  • 11. ● Various Modes for opening a text file are: Mode Description “r” Read Default value. Opens a file for reading, error if the file does not exist. “w” Write Opens a file for writing, creates the file if it does not exist “a” Append Opens a file for appending, creates the file if it does not exist “r+” Read and Write File must exist otherwise error is raised.Both reading and writing operations can take place. “w+” Write and Read File is created if it does not exist.If the file exists past data is lost (truncated).Both reading and writing operations can take place. “a+” Append and Read File is created if it does not exist.If the file exists past data is not lost .Both reading and writing(appending) operations can take place. 12
  • 12. CLOSING A FILE ● close()- method will free up all the system resources used by the file, this means that once file is closed, we will not be able to use the file object any more. ● <fileobject>. close() will be used to close the file object, once we have finished working on it. Syntax: <fileObject>.close() Example : f.close() ● It is important to close your files, as in some cases, due to buffering,changes made to a file may not show until you close the file. 13
  • 13. READING FROM A FILE ➔ A Program reads a text/binary file from hard disk. Here File acts like an input to the program. ➔ Followings are the methods to read a data from the file: ◆ read() METHOD ◆ readline() METHOD ◆ readlines() METHOD 14
  • 14. read() METHOD ● By default the read() method returns the whole text, but you can also specify how many characters you want to return by passing the size as argument. Syntax: <file_object>.read([n]) where n is the size ● To read entire file : <file_object>.read() ● To reads only a part of the File : <file_object>.read(size) f = open("demo.txt", "r") print(f.read(15)) Returns the 15 first characters of the file "demo.txt". 15
  • 15. 16
  • 16. readline() METHOD ● readline() will return a line read, as a string from the file. Syntax: <file_object>.readline() ● Example f = open("demo.txt", "r") print(f.readline()) ● This example program will return the first line in the file “demo.txt” irrespective of number of lines in the text file. 17
  • 17. Reading a complete file line by line using readline(). 18
  • 18. readlines() METHOD ● readlines() method will return a list of strings, each separated by n ● readlines() can be used to read the entire content of the file. . Syntax: <file_object>.readlines() ● It returns a list, which can then be used for manipulation. Example : f = open("demofile.txt", "r") print(f.readlines()) 19
  • 19. Read a file using Readlines() 20
  • 20. 21
  • 21. WRITING TO A TEXT FILE ● A Program writes into a text/binary file in hard disk. ● Followings are the methods to write a data to the file. ○ write () METHOD ○ writelines() METHOD ● To write to an existing file, you must add a parameter to the open() Function which specifies the mode : ○ "a" - Append - will append to the end of the file ○ "w" - Write - will overwrite any existing content 22
  • 22. write() Method ● write() method takes a string ( as parameter ) and writes it in the file. ● For storing data with end of line character, you will have to add n character to end of the string ● Example: Open the file "demo_append.txt" and append content to the file: f = open("demo_write.txt", ""a) f.write("Hello students n We are learning data file handling…..!") f.close() f = open("demo_write.txt", "r") #open and read the file after the appending print(f.read()) 23
  • 23. 24
  • 24. writelines() METHOD ● For writing a string at a time, we use write() method, it can't be used for writing a list, tuple etc. into a file. ● Python file method writelines() writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. ● So, whenever we have to write a sequence of string, we will use writelines(), instead of write(). 25
  • 25. 26
  • 26. The flush() The flush function forces the writing of data on disc still pending on the output buffer. Syntax : <file_object>.flush() 27
  • 27. 28
  • 28. Standard Input, Output, and Error Streams ❏ Keyboard is the standard input device ❏ stdin - reads from the keyboard ❏ Monitor is the standard output device. ❏ stdout - prints to the display ❏ If any error occurs it is also displayed on the monitor and hence it is also the standard error device. ❏ Same as stdout but normally only for errors (stderr) The standard devices are implemented as files called streams. They can be used by importing the sys module. 29
  • 29. DATA FILE HANDLING IN BINARY FILES ● Files that store objects as some byte stream are called binary files. ● That is, all the binary files are encoded in binary format , as a sequence of bytes, which is understood by a computer or machine. ● In binary files, there is no delimiter to end the line. ● Since they are directly in the form of binary, there is no need to translate them. ● But they are not in human readable form and hence difficult to understand. 30
  • 30. ● Objects have a specific structure which must be maintained while storing or accessing them. ● Python provides a special module called pickle module for this. ● PICKLING refers to the process of converting the structure to a byte stream before writing to a file. ● UNPICKLING is used to convert the byte stream back to the original structure while reading the contents of the file. 31
  • 32. PICKLE Module ● Before reading or writing to a file, we have to import the pickle module. import pickle ● It provides two main methods : ○ dump() method ○ load() method 33
  • 33. Opening and closing binary files Opening a binary file: Similar to text file except that it should be opened in binary mode.Adding a ‘b’ to the text file mode makes it binary - file mode. EXAMPLE : f = open(“demo.dat”,”rb”) Closing a binary file f.close() 34
  • 34. ● Various Modes for opening a binary file are: Mode Description “rb” Read Default value. Opens a file for reading, error if the file does not exist. “wb” Write Opens a file for writing, creates the file if it does not exist “ab” Append Opens a file for appending, creates the file if it does not exist “r+b”or “rb+” Read and Write File must exist otherwise error is raised.Both reading and writing operations can take place. “w+b”or “wb+” Write and Read File is created if it does not exist.If the file exists past data is lost (truncated).Both reading and writing operations can take place. “a+b” or “ab+” Append and Read File is created if it does not exist.If the file exists past data is not lost .Both reading and writing operations can take place. 35
  • 35. pickle.dump() Method ● pickle.dump() method is used to write the object in file which is opened in binary access mode. Syntax : pickle.dump(<structure>,<FileObject>) ● Structure can be any sequence in Python such as list, dictionary etc. ● FileObject is the file handle of file in which we have to write. 36
  • 37. pickle.load() Method ● pickle.load() method is used to read data from a file Syntax : <structure> = pickle.load(<FileObject>) ● Structure can be any sequence in Python such as list, dictionary etc. ● FileObject is the file handle of file in which we have to write. 38
  • 38. 39
  • 39. Write a method to write employee details into a binary file. Take the input from the user. Employee Details: Employee Name Employee Number Department Salary 40
  • 40. Random Access in Files : tell() and seek() ❏ tell() function is used to obtain the current position of the file pointer Syntax : f.tell() ❏ File pointer is like a cursor, which determines from where data has to be read or written in the file. ❏ seek () function is used to change the position of the file pointer to a given position. Syntax : f.seek(offset,reference_point) Where f is the file object 41
  • 41. CSV files ● CSV stands for Comma Separated Values.It is a type of plain text file that uses specific structuring to arrange tabular data such as a spreadsheet or database. ● CSV like a text file , is in a human readable format and extensively used to store tabular data, in a spreadsheet or database. ● Each line of the file is a data record. ● Each record consists of one or more fields, separated by commas. ● The separator character of CSV files is called a delimiter. ● Default delimiter is (,). ● Other delimiters are tab(t), colon (:), pipe(|), semicolon (;) characters. 42
  • 42. Python CSV Module ● CSV module provides two types of objects : ○ reader : to read from cvs files ○ writer : to write into csv files. ● To import csv module in our program , we use the following statement: import csv 43
  • 43. Opening / Closing a CSV File ● Open a CSV File : f = open(“demo_csv.csv”,”r”) OR f = open(“demo_csv.csv”,”w”) ● Close a CSV File: f.close() 44
  • 44. Role of argument newline in opening of csv files : ● newline argument specifies how would python handle new line characters while working with csv files on different Operating System. ● Additional optional argument as newline = “”(null string) with the file open() will ensure that no translation of EOL character takes place. 45
  • 45. Steps to write data to a csv file 1. Import csv module import csv 1. Open csv file in write mode. f = open(“csv_demo.csv”,”w”) 1. Create the writer object. demo_writer = csv.writer(f) 1. Write data using the methods writerow() or writerows() demo_writer.writerow(<iterable_object>) 1. Close the file f.close() 46
  • 46. Writing in CSV Files ● csv.writer() : Returns a writer object which writes data into csv files. ● writerow() : Writes one row of data onto the writer object. Syntax : <writer_object>.writerow() ● writerows() : Writes multiple rows into the writer object Syntax : <writer_object>.writerow() 47
  • 47. Writing in CSV Files ● To write data into csv files, writer() function of csv module is used. ● csv.writer(): ○ Returns a writer object which writes data into writer object. ● Significance of writer object ○ The csv.writer() returns a writer object that converts the data into a delimited string. ○ The string can be later converted into csv files using the writerow() or writerows() method. 48
  • 48. ● <writer_object>.writerow() : Writes one row of data in to the writer object. ● <writer_object>.writerows() Writes multiple rows into the writer object. 49
  • 49. 50
  • 50. Reading from CSV Module ● To read data from csv files, reader function of csv module is used. ● csv.reader() : Returns a reader object. It loads data from a csv file into an iterable after parsing delimited data. 51
  • 51. Steps to read data from a csv file 1. Import csv module import csv 1. Open csv file in read mode. f = open(“csv_demo.csv”,”r”) 1. Create the reader object. demo_reader = csv.reader(f) 1. Fetch data through for loop, row by row. 1. Close the file f.close() 52
  • 52. 53
  • 53. QUESTIONS FOR PRACTICE Write a method in python to read the content from a file “Poem.txt” and display the same on the screen. Write a method in python to read the content from a file “Poem.txt” line by line and display the same on the screen. Write a method in python to count the number of lines from a text file which are starting with an alphabet T. Write a method in Python to count the total number of words in a file 54
  • 54. Write a method in python to read from a text file “Poem.text” to find and display the occurrence of the word “Twinkle” Write a method Bigline() in Python to read lines from a text file “Poem.txt” and display those lines which are bigger than 50 characters. Write a method to read data from a file. All the lowercase letter should be stored in the file “lower.txt” , all upper case characters get stored inside the file “upper.txt” and other characters stored inside the file “others.txt” 55