0% found this document useful (0 votes)
7 views32 pages

Lecture 17- File Processing

Uploaded by

Abdullah Madni
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)
7 views32 pages

Lecture 17- File Processing

Uploaded by

Abdullah Madni
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

Lecture 17

File Processing
Fall 2021-BSCS (11-A)

Shah Khalid
Email: [Link]@[Link]

National University of Sciences and Technology


1 1
Today…
• Last Session:
• List, Tuples, (Dictionaries)

• Today’s Session:
• Files:
• Why Files
• File Processing
• File Functions
• Examples

• Next- GUI
Files
• All data that we store in lists, tuples, and dictionaries within any
program are lost when the program ends
• These data structures are kept in volatile memory (i.e., RAM)

• To save data for future accesses, we can use files, which are stored on
non-volatile memory (usually on disk drives)

• Files can contain any data type, but the easiest files to work with are
those that contain text
• You can think of a text file as a (possibly long) string that happens to be stored
on disk!
File Processing
• Python has several functions for creating, reading, updating, and
deleting files

• To create and/or open an existing file in Python, you can use the
open() function as follows:
• <variable> = open(<file_name>, <mode>)

• <variable> is a file object that you can use in your program to process
(i.e., read, write, update, or delete) the file
File Processing
• <file_name> is a string that defines the name of the file on disk

• <mode> can be only 1 of the following four modes:


• "r“: This is the default mode; It allows opening a file for reading; An error will
be generated if the file does not exist
• "a“: It allows opening a file for appending; It creates the file if it does not exist
• "w“: It allows opening a file for writing; It creates the file if it does not exist
• "x“: It allows creating a specified file; It returns an error if the file exists
File Processing
• In addition, you can specify if the file should be handled as a binary or
text file
• "t“: This is the default value; It allows handling the file as a text file
• "b“: It allows handling the file as a binary file

• Example:
• f = open("[Link]") is equivalent to f = open("[Link]“, “rt”)
• When opening a file for reading, make sure it exists, or otherwise you will get
an error!
Reading a File
• The open() function returns a file object, which has a read() method
for reading the content of the file

f = open("[Link]", "r")
data = [Link]()
print(data)
print(type(data))

The type of data is str, which you can parse as usual!


Reading a File
• You can also specify how many characters to return from a file using
read(x), where x is the first x characters in the file

f = open("[Link]", "r")
data = [Link](10)
This will return the first
print(data) 10 characters in the file
print(type(data))
Reading a File
• You can also use the function readline() to read one line at a time

f = open("[Link]", "r")
This file contains some information about sales
str1 = [Link]()
print(str1)
Total sales today = QAR100,000
str2 = [Link]()
print(str2)
Sales from PCs = QAR70,000
print([Link]())

This is the content of the file


Reading a File
• You can also use the function readline() to read one line at a time

f = open("[Link]", "r")
This file contains some information about sales
str1 = [Link]()
print(str1)
Total sales today = QAR100,000
str2 = [Link]()
print(str2)
Sales from PCs = QAR70,000
print([Link]())

Note that the string returned by readline() will always end with a newline, hence, two
newlines were produced after each sentence, one by readline() and another by print()
Reading a File
• You can also use the function readline() to read one line at a time

f = open("[Link]", "r")
str1 = [Link]()
print(str1, end = “”) This file contains some information about sales
str2 = [Link]() Total sales today = QAR100,000
print(str2, end = “”) Sales from PCs = QAR70,000
print([Link](), end = “”)

Only a solo newline will be generated by readline(), hence, the output on the right side
Looping Through a File
• Like strings, lists, tuples, and dictionaries, you can also loop through a
file line by line

f = open("[Link]", "r")
This file contains some information about sales
Total sales today = QAR100,000
for i in f:
Sales from PCs = QAR70,000
print(i, end = "")

Again, each line returned will produce a newline, hence, the usage of the end keyword
in the print function
Writing to a File
• To write to a file, you can use the “w” or the “a” mode in the open()
function alongside the write() function as follows:
f = open("[Link]", "w")
[Link]("This file contains some information about sales\n")
[Link]("Total sales today = QAR100,000\n")
[Link]("Sales from PCs = QAR70,000\n")
[Link]()

Every time we run this code, the same above content will be written (NOT
appended) to [Link] since we are using the “w” mode
If, alternatively, we use the “a” mode, each time we run the code, the same
above content will be appended to the end of [Link]
Writing to a File
• To write to a file, you can use the “w” or the “a” mode in the open()
function alongside the write() function as follows:
f = open("[Link]", "w")
[Link]("This file contains some information about sales\n")
[Link]("Total sales today = QAR100,000\n")
[Link]("Sales from PCs = QAR70,000\n")
[Link]()

Also, once we are finished writing to the file, we should always close it using
the close() function. This will ensure that the written content are pushed from
volatile memory (i.e., RAM) to non-volatile memory (i.e., disk), thus preserved
Writing to a File
• You can also write information into a text file via the already familiar
print() function as follows:

f = open("[Link]", "w")
print("This file contains some information about sales", file = f)
print("Total sales today = QAR100,000", file = f)
print("Sales from PCs = QAR70,000", file = f)
[Link]()

This behaves exactly like a normal print, except that the result will be sent to a file
rather than to the screen
Deleting a File
• To delete a file, you must first import the OS module, and then run
its [Link]() function
import os
[Link]("[Link]")
• You can also check if the file exists before you try to delete it
import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")
Task For Students
Example: Copy a File
import os
Home Task
def copyFile(name):
if type(name) is str and [Link](name):
l = [Link](".")
new_name = l[0] + "_copy." + l[1]
f_source = open(name, "r")
f_destination = open(new_name, "w")
f_destination.write(f_source.read())
f_source.close()
f_destination.close()
else:
print("The file does not exist!")

copyFile("[Link]")
Example: Word Count
Home Task
• A common utility on Unix/Linux systems is a small program called
“wc” which, if called for any file, returns the numbers of lines, words,
and characters contained therein

• We can create our version of “wc” in Python as follows:


import os

def wordCount(name):
if type(name) is str and [Link](name):
f = open(name)
l_c = 0
w_c = 0
Example: Word Count
c_c = 0
for i in f:
l_c = l_c + 1
list_of_words = [Link]()
w_c = w_c + len(list_of_words)
for j in list_of_words:
c_c = c_c + len(j)
dic = {"Line Count": l_c, "Word Count": w_c, "Character Count": c_c}
return dic
else:
print("The file does not exist!")

print(wordCount("[Link]"))
File Processing Practice
Examples –Questions
Example 1:
• Write a function in python to read the content from a text file
"[Link]" line by line and display the same on screen
Example 2:
• Write a function in python to count the number of lines from a text
file "[Link]" which is not starting with an alphabet "T“
• Example: If the file "[Link]" contains the following lines: A boy is
playing there.
There is a playground.
An aeroplane is in the sky.
The sky is pink.
Alphabets and numbers are allowed in the password.

• The function should display the output as 3


Cont…
Example 3:
• Write a function in Python to count and display the total number of
words in a text file.
Example 4
• Write a function in Python to read lines from a text file "[Link]".
Your function should find and display the occurrence of the word
"the“
• For example: If the content of the file is:
“China is the fastest-growing economy. China is looking for more
investments around the globe. The whole world is looking at China as
a great market. Most of the Chinese can foresee the heights that
China is capable of reaching."
• The output should be 5.
Cont…
Example 5:
• Write a function display_words() in python to read lines from a text
file "[Link]", and display those words, which are less than 4
characters.
Example 6
• Write a function in Python to count the words "this" and "these"
present in a text file "[Link]". [Note that the words "this" and
"these" are complete words]
Example 7:
• Write a function in Python to count words in a text file those are
ending with alphabet "e".
Example 8:
• Write a function in Python to count uppercase character in a text file.
Programming…
• Practice…………………

• Next Project Presentation

You might also like