0% found this document useful (0 votes)
5 views75 pages

Plus 09 Python Reading Files

The document provides a comprehensive guide on reading files in Python, covering the open() function, mode parameters, and various reading methods such as .read(), .readline(), and .readlines(). It emphasizes the importance of closing files and introduces the use of loops for efficient file reading. Additionally, it includes practical tasks for readers to apply their knowledge on file handling.

Uploaded by

bulent
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)
5 views75 pages

Plus 09 Python Reading Files

The document provides a comprehensive guide on reading files in Python, covering the open() function, mode parameters, and various reading methods such as .read(), .readline(), and .readlines(). It emphasizes the importance of closing files and introduces the use of loops for efficient file reading. Additionally, it includes practical tasks for readers to apply their knowledge on file handling.

Uploaded by

bulent
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
You are on page 1/ 75

Reading Files

Table of Contents
▶ open() Function
▶ mode Parameter
▶ Reading the Files with .read() Method
▶ Reading the Files with .readline() Method
▶ Reading the Files with .readlines() Method
▶ Reading the Files with Loops
▶ The Matter of Closing the Files
1 open() Function
How was your pre-class content. Did you understand the
“Reading Files with Python”?
open() Function (review)
▸ Parameters of the open() function :

open (file, mode='r', buffering=-1, encoding=None,


errors=None, newline=None, closefd=True, opener=None)

6
open() Function (review)
▸ We will mostly examine and work with some of the following parameters of the open()
function :

open (file, mode='r', buffering=-1, encoding=None,


errors=None, newline=None, closefd=True, opener=None)

file

encoding

mode
7
open() Function (review) file

▸ file is the only required parameter of the open()


function. This parameter is a path-like object which is a
str or bytes that represents a path in the file directory.

open ("file_name_and_path")

8
open() Function (review)
▸ You can see the current path of your Jupyter
using pwd command.

9
open() Function (review) file

▸ In the following example, you see that we open a .txt


file object. We passed the required parameter (file)
into the open() function.

10
open() Function (review) file

11
open() Function (review) encoding

▸ We can open a file in the same way by using the


following syntax :

12
I have learned enough about the encoding parameter
so far.

True False
mode

2 mode Parameter
mode Parameter (review)
Character What it's used for?

'r' Open for reading (default). If the file doesn't exist, FileNotFoundError will raise.

Open for writing. It will append to the end of the file if it already exists. If there is no file, it will
'a' create it.

'w' Open for writing. It will be overwritten if the file already exists. If there is no file, it will create it.

'x' Open for exclusive creation, it will fail if the file already exists.

'b' Open in binary mode.

't' Open as a text file (default).

'+' Open for updating (reading and writing).


15
mode Parameter (review)
▸ By default, open() function executes opening the file for
reading ('r') as a text ('t'). In other words, it defaults to 'r'
or 'rt' which means open for reading in text mode.

16
mode Parameter (review)
▸ Another important point we should cover about mode is that
you can choose the format in which you want to open the
file as text ('t') or binary ('b').
com mos
mo t
'b' 't' nu
se

Returns contents as The contents of


bytes objects the file are
without any returned as str.
decoding. It’s default for mode
parameter.
17
Reading Methods
▸ You can use the following methods for reading a file :

.read(size)

.readline(size)

.readlines()

using loops
18
3 Reading the Files
with .read() Method
Reading Methods
▸ Create a text file manually named fishes.txt :

fishes.txt

Orca is a kind of Dolphin.


Blue Whale is the largest animal known on earth.
Sharks are the sister group to the Rays (batoids).
The Tuna Fish can weigh up to 260 kg.
Squid and Octopus are in the same class.

20
Reading Methods

Keep in your mind!

You can pass full path of the file into open() function. So
that, when the file path is entered, the location where the
file is saved does not matter.

file = open("C:/users/desktop/fishes.txt", "r")

21
Basic Structure of Working with Files

file = open("file_name", "r")

...
body
...

file.close()

22
.read() Method (review)
▸ Reading all content at once :

23
.read() Method (review)
▸ The output :

24
.read() Method (review)
▸ Reading limited number of characters :

What is the output? Try to


figure out in your mind...

25
.read() Method (review)
▸ The output :

26
.read() Method (review)
▸ Now let's continue to read using the size
parameter.

What is the output? Try to


figure out in your mind...

27
.read() Method (review)
▸ The output :

28
.read() Method (review)
▸ Now let's continue to read using the size parameter.

What is the output? Try to


figure out in your mind...

29
.read() Method (review)
▸ The output :

30
.read() Method (review)
▸ Find the cursor :

What is the output? Try to


figure out in your mind...

31
.read() Method (review)
▸ The output :

32
.read() Method
▸ Task :
○ Create a txt file named rumi.txt in your
current working directory consisting of the
following quotes of Rumi.
rumi.txt

I want to sing
Like the birds sing,
Not worrying about
Who hears or
What they think.
33
.read() Method
▸ Task (continued):
○ Create a txt file named rumi.txt in your
current directory consisting of the following
quotes of Rumi.
○ Read and display the entire contents of this
file at once.
○ Display the first two lines using read()
method.
34
.read() Method (review)
▸ Task (continued):
○ Display the next 13 chars of the content,
○ Display the current location of the cursor,
○ Bring the cursor onto beginning of the
second line and display the second line again.
○ Close the file.

35
.read() Method (review)
▸ The entire code block can be as follows (suppose you’ve
created the rumi.txt manually into your current directory:

36
.read() Method (review)
▸ The output :

First 35 chars
(first two lines)

The next 13 chars

The current location


of the cursor

37
Reading the Files
4 with .readline() Method
.readline() Method (review)
▸ Reading text files line by line :

What is the output? Try to


figure out in your mind...

39
.readline() Method (review)
▸ The output :

40
.readline() Method (review)
▸ So that, first line of text consists of 27 characters.
Let's choose 13 as the size parameter and see what
happens :

fishes.txt

Orca is a kind of Dolphin.


Blue Whale is the largest animal known on earth.
Sharks are the sister group to the Rays (batoids).
The Tuna Fish can weigh up to 260 kg.
Squid and Octopus are in the same class.

41
.readline() Method (review)

fishes.txt

Orca is a kind of Dolphin.


Orca is a kind of Dolphin.\n
Blue Whale is the largest animal known on earth.
Sharks are the sister group to the Rays (batoids).
|||||||||||||||||||||||||||=27
The Tuna Fish can weigh up to 260 kg.
Squid and Octopus are in the same class.

42
.readline() Method (review)

What is the output? Try to


figure out in your mind...

43
.readline() Method (review)

when a line ends, whatever


\n is the last char of the size parameter is, it goes
the first line ahead to the next line

default empty
line

44
.readline() Method
▸ Task :
○ Consider the rumi.txt file you created before.
rumi.txt

I want to sing
Like the birds sing,
Not worrying about
Who hears or
What they think.

45
.readline() Method
▸ Task (continued) :
○ Read and display the first line of this file,
○ Read and display the second line of this file,
○ Read and display the third line of this file
using size parameter in the method,
○ Close the file.

46
.readline() Method
▸ The entire code block can be as follows (suppose you’ve
created the rumi.txt manually into your current directory:

47
.readline() Method
▸ The output :

reading of 18 chars
displays the third line

48
Reading the Files
5 with .readlines() Method
.readlines() Method (review)
▸ Using our same text file, let's look at the following
example on how the output looks like :

What is the output? Try to


figure out in your mind...

50
.readlines() Method (review)
▸ The output :

51
.readlines() Method (review)
▸ Let's take a look at the following example where
.readline() and .readlines() are used together.

What is the output? Try to


figure out in your mind...

52
.readlines() Method (review)
▸ The output :

53
.readlines() Method (review)
▸ You may have noticed that the type of the
sea.readlines() object is the list. Let's see it :

54
.readlines() Method
▸ Task :
○ Consider the rumi.txt file you created before.
rumi.txt

I want to sing
Like the birds sing,
Not worrying about
Who hears or
What they think.

55
.readlines() Method
▸ Task (continued) :
○ Read and display the entire file in a list form,
○ Close the file.

56
.readlines() Method
▸ The entire code block can be as follows (suppose you’ve
created the rumi.txt manually into your current directory:

57
.readlines() Method
▸ The output :

58
6 Reading the Files
with loops
Reading the Files with Loops(review)
▸ The most efficient way to read the contents of a file is
using the for loop. Let's take a look at an example of
how we do this.

What is the output? Try to


figure out in your mind...

60
Reading the Files with Loops(review)
▸ The output :

61
Reading

the Files with Loops(review)
Since the type of sea.readlines() object is a list, we can use it as an iterator and read the
whole file in the same way.

62
Reading the Files with Loops
▸ Task :
○ Consider the rumi.txt file you created before.
rumi.txt

I want to sing
Like the birds sing,
Not worrying about
Who hears or
What they think.

63
Reading the Files with Loops
▸ Task (continued) :
○ Read and display the entire file with loops
using file-like object as an iterator,
○ Read and display the entire file with loops
using .readlines()-produced list as an
iterator,
○ Close the file.

64
Reading the Files with Loops
▸ The entire code block can be as follows (suppose you’ve
created the rumi.txt manually into your current directory:

f is file-like object and


it’s used as an iterator

65
Reading the Files with Loops
▸ The output :

66
Reading the Files with Loops
▸ The entire code block can be as follows (suppose you’ve
created the rumi.txt manually into your current directory:

f.readlines() is a
list type and it’s used
as an iterator
67
Reading the Files with Loops
▸ It gives the same output :

68
7 The Matter of Closing Files
The Matter of Closing the Files(review)
Workflow of working with files to be followed

opening the file Working Closing the file


with the file

70
The Matter of Closing the Files(review)
▸ Syntax of working with files :

with open("my_file.txt", "r", encoding="utf-8") as f:


code block

71
The Matter of Closing the Files(review)
▸ Take a look at the way we use it :

72
Using the with … as … You can complete this
block assignment by yourself or
● Create another txt file, in a group session later.

● Implement the same steps


(reading methods) in the
tasks shown in this
presentation.
How well did you like this lesson?
THANKS!
End of the Lesson
(Reading Files)
next Lesson

Writing Files

click above Powered by

You might also like