0% found this document useful (0 votes)
2 views43 pages

Mod 4

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

Mod 4

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

Computational Thinking using

Python Programming

Module 4

Dr. R Arokia Priya Charles

D Y Patil International University School of Engineering


Syllabus
• Prerequisites: None

• Course Objectives:

1. Comprehend the basic concepts of programming languages and their structures.

2. Develop problem-solving skills using programming techniques.

3. Learn to write, debug, and optimize code.

4. Apply programming concepts to semiconductor engineering problems.

• Course Outcomes: (CO1-CO5 for 5 modules)

• CO1004.1: Students will be able to explain the fundamental components of programming languages, including syntax, semantics, data types, and control structures.

• CO1004.2: Students will enhance their logical thinking and creativity by solving a range of programming challenges and exercises.

• CO1004.3: Students will create their own functions and handle the exceptions

• CO1004.4: Students will be able to efficiently manage files, perform read/write operations

• CO1004.5: Students will be able to create and manage GUI applications, understand components and events, and utilize various widgets like buttons, entries, texts,
and check buttons effectively.

D Y Patil International University School of Engineering


Syllabus

Module – IV File Handling (06 Hrs)

File handling Modes, Reading Files, Writing & Appending to Files, Handling File Exceptions
The with statement. Examples of use of Python libraries like numpy, pandas and matplotlib in
File handling

D Y Patil International University School of Engineering


Examination

School of Semiconductor Engineering


Examination Pattern Academic Year 2024-25

Sr.No Name of the Course Name of the Faculty Examination


Mid Sem (20 End Sem (50
Concurrent (30 Marks) Marks) Marks)

Tool 1 (10) Tool 2 (10) Tool 3 (10)

Computational
thinking with Python Hacker rank
1 Programming Dr. Priya Charles Quiz Project pgmming

D Y Patil International University School of Engineering


Introduction
 FILE HANDLING is a mechanism by which we can read data of disk
files in python program or write back data from python program to
disk files.
 So far in our python program the standard input in coming from
keyboard an output is going to monitor i.e. no where data is stored
permanent and entered data is present as long as program is running
BUT file handling allows us to store data entered through python
program permanently in disk file and later on we can read back the
data

D Y Patil International University School of Engineering


D Y Patil International University School of Engineering
DATA FILES

 It contains data pertaining to a specific application, for


later use. The data files can be stored in two ways –
 Text File
 Binary File
 Csv(comma separated files)

D Y Patil International University School of Engineering


Text File
 Text file stores information in ASCII OR UNICODE character. In
text file everything will be stored as a character for example if
data is “computer” then it will take 8 bytes and if the data is
floating value like 11237.9876 it will take 10 bytes.

 In text file each like is terminated by special character called


EOL. In text file some translation takes place when this EOL
character is read or written. In python EOL is ‘\n’ or ‘\r’ or
combination of both

D Y Patil International University School of Engineering


Binary files

 It stores the information in the same format as in the memory i.e.


data is stored according to its data type so no translation occurs.

 In binary file there is no delimiter for a new line

 Binary files are faster and easier for a program to read and write than
text files.

 Data in binary files cannot be directly read, it can be read only through
python program for the same.

D Y Patil International University School of Engineering


CSV

D Y Patil International University School of Engineering


What You Need In Order To Read
Information From A File

1. Open the file and associate the file with a file variable.
2. A command to read the information.
3. A command to close the file.

D Y Patil International University School of Engineering


Steps in Data File Handling

1. OPENING FILE
 We should first open the file for read or write by specifying the name of file and
mode.

2. PERFORMING READ/WRITE
 Once the file is opened now we can either read or write for which file is opened
using various functions available

3. CLOSING FILE
 After performing operation we must close the file and release the file for other
application to use it,

D Y Patil International University School of Engineering


Opening File

 File can be opened for either – read, write, append.

SYNTAX:
file_object = open(filename)
Or
file_object = open(filename,mode)

** default mode is
“read”

D Y Patil International University School of Engineering


Opening File

myfile = open(“story.txt”)
here disk file “story.txt” is loaded in RAM

memory and its reference is linked to File

“myfile” object, now python program


will access “story.txt” through “myfile”
object.
myfile

here “story.txt” is present in the


same folder where .py file is stored
otherwise if disk file to work is in
another folder we have to give full path.
D Y Patil International University School of Engineering
Opening File

myfile = open(“article.txt”,”r”)
here “r” is for read (although it is by default, other
options are “w” for write, “a” for append)

myfile = open(“d:\\mydata\\poem.txt”,”r”)
here we are accessing “poem.txt” file stored in
separate location i.e. d:\mydata folder.
at the time of giving path of file we must use double backslash(\\) in place of single
backslash because in python single slash is used for escape character and it may cause
problem like if the folder name is “nitin” and we provide path as d:\nitin\poem.txt then
in \nitin “\n” will become escape character for new line, SO ALWAYS USE DOUBLE
BACKSLASH IN PATH

D Y Patil International University School of Engineering


B.Positioning The File Pointer
letters.txt
A

B
:

D Y Patil International University School of Engineering


Opening File
myfile = open(“article.txt”,”r”)
here “r” is for read (although it is by default, other
options are “w” for write, “a” for append)

myfile = open(“d:\\mydata\\poem.txt”,”r”)
here we are accessing “poem.txt” file stored in separate location i.e. d:\mydata
folder.
at the time of giving path of file we must use double backslash(\\) in place of single
backslash because in python single slash is used for escape character and it may cause
problem like if the folder name is “nitin” and we provide path as d:\nitin\poem.txt then in
\nitin “\n” will become escape character for new line, SO ALWAYS USE DOUBLE
BACKSLASH IN PATH

D Y Patil International University School of Engineering


Opening File

myfile = open(“d:\\mydata\\poem.txt”,”r”)

another solution of double backslash is using “r” before the path


making the string as raw string i.e. no special meaning attached to
any character as:

myfile = open(r“d:\mydata\poem.txt”,”r”)

D Y Patil International University School of Engineering


File Access Mode
Text Binary Description Notes
File File
Mode Mode
‘r’ ‘rb’ Read only File must exists, otherwise Python raises
I/O errors
‘w’ ‘wb’ Write only If file not exists, file is created
If file exists, python will truncate existing data and
overwrite the file.
‘a’ ‘ab’ Append File is in write mode only, new data will be added to the end
of existing data i.e. no overwriting. If file not exists it is
created
‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised Both reading and
writing can take place
w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data will be truncated,
both read and write allowed
‘a+’ ‘a+b’ or ‘ab+’, , Write and read Same as above but previous content will be retained and
both read and write.

D Y Patil International University School of Engineering


Closing file

 As reference of disk file is stored in file handle so to close we must


call the close() function through the file handle and release the file.

myfile.close()

Note: open function is built-in function used standalone while close() must
be called through file handle

D Y Patil International University School of Engineering


Reading from File
 To read from file python provide many functions like :

 Filehandle.read([n]) : reads and return n bytes, if n is not


specified it reads entire file.

 Filehandle.readline([n]) : reads a line of input. If n is specified


reads at most n bytes. Read bytes in the form of string ending
with line character or blank string if no more bytes are left for
reading.

 Filehandle.readlines(): reads all lines and returns them in a list

D Y Patil International University School of Engineering


Example-1: read()
SAMPLE
FILE

D Y Patil International University School of Engineering


Example-1: read()
SAMPLE
FILE

D Y Patil International University School of Engineering


Example-2: read()
SAMPLE
FILE

D Y Patil International University School of Engineering


Example-3: readline()
SAMPLE
FILE

D Y Patil International University School of Engineering


Example-3: readline()
SAMPLE
FILE

HAVE YOU NOTICED THE DIFFERENCE IN OUTPUT FROM


PREVIOUS OUPUT?
D Y Patil International University School of Engineering
Example-3: readline() line by line
SAMPLE
FILE

D Y Patil International University School of Engineering


Example-5: reading line by line using for loop
SAMPLE
FILE

D Y Patil International University School of Engineering


Example-6: Calculating size of file with and without EOL and
blank lines
SAMPLE
FILE

D Y Patil International University School of Engineering


Example-7: readlines()
SAMPLE
FILE

D Y Patil International University School of Engineering


Example-8 & 9: counting size of files in byte and no. of lines
SAMPLE
FILE

D Y Patil International University School of Engineering


Questions…

D Y Patil International University School of Engineering


Writing onto files

 After read operation, let us take an example of how to write data


in disk files. Python provides functions:
 write ()
 writelines()
 The above functions are called by the file handle to write
desired content.

Name Syntax Description


write() Filehandle.write(str1) Writes string str1 to file
referenced by filehandle

Writelines() Filehandle.writelines(L) Writes all string in List L as


lines to file referenced by
filehandle.

D Y Patil International University School of Engineering


Example-1:
write() using “w”
mode

RAKA
SHAKAAL
GABBAR

D Y Patil International University School of Engineering


Example-1:
write() using “w”
mode

Lets run
the same
program
again
D Y Patil International University School of Engineering
Example-1:
write() using “w”
mode

Now we can observe that while writing data to file using “w”
mode the previous content of existing file will be overwritten and
new content will be saved.

If we want to add new data without overwriting the previous


content then we should write using “a” mode i.e. append mode.

D Y Patil International University School of Engineering


Example-2:
write() using “a”
mode

New content is
added after
previous
content
D Y Patil International University School of Engineering
Example-3:
using
writelines()

D Y Patil International University School of Engineering


Example-4: Writing String as a record to file

D Y Patil International University School of Engineering


Example-4: To copy the content of one file to another file

D Y Patil International University School of Engineering


flush() function

 When we write any data to file, python hold


everything in buffer (temporary memory) and
pushes it onto actual file later. If you want to force
Python to write the content of buffer onto storage,
you can use flush() function.

 Python automatically flushes the files when closing


them i.e. it will be implicitly called by the close(),
BUT if you want to flush before closing any file you
can use flush()

D Y Patil International University School of Engineering


Example: working of flush()
Without Nothing is
flush() in the file
temp.txt

When you run the above code,


program will stopped at “Press any
key”, for time being don’t press
any key and go to folder where file
“temp.txt” is created an open it to
see what is in the file till now
NOW PRESS ANY KEY….

Now content is
stored, because of
close() function
contents are flushed

pushed in
D Y Patil International University file School of Engineering
Example: working of flush()
With flush() All
contents
before
flush() are
present in
file

When you run the above code,


program will stopped at “Press any
key”, for time being don’t press
any key and go to folder where file
“temp.txt” is created an open it to
see what is in the file till now
NOW PRESS ANY KEY….

Rest of the content is


written because of
close(), pushed
contentsinare
file.
flushed and

D Y Patil International University School of Engineering

You might also like