Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

P.

1 of 9

Contents

Files ................................................................................................................................ 2
Read from Files....................................................................................................... 2
read() function ............................................................................................... 2
Further elaboration ................................................................................ 3
readline() function ......................................................................................... 4
readlines() function ........................................................................................ 6
Further elaboration ................................................................................ 7
Write to Files .......................................................................................................... 8
Classwork 1 ............................................................................................................ 9
P. 2 of 9

Files
A file in computer file is a chunk of logically related data or information which can be
used by computer programs. Usually a file is kept on a permanent storage media, e.g.
a hard disk. A unique name and path is used by human users, programs or scripts to
access a file for purposes of reading and modification.

Read from Files


read() function
Suppose you have a text file called lovePoem.txt with the contents as follows:

You may grab its whole contents by writing the following Python script
(readWholeFile.py):

# r is the File Access Mode


# It means open file for reading
# fobj is the File Object
fobj = open("lovePoem.txt", "r")

# Grab the whole content of the text file


# by using read()
print(fobj.read())

# Close the file object when


# it is not in use
fobj.close()
P. 3 of 9

ch = input("")

The output should be:

Further elaboration

The way of telling Python to read from a file is using the open( ) function. The first
parameter is the name of the file we want to read and the second parameter,
assigned with value "r", stating that we would like to read from the file.

The open() function returns a file object, which offers attributes and methods.

The read() function reads all text from a file into a string. We usually use this
method to manipulate the whole text of that file.

After we have finished working with a file, simply close it again by using the file
object method close( ).
P. 4 of 9

readline() function
There are other ways to read the contents of a text file. In the coming example
readline.py, it will demonstrate the way to text file line by line through using the
readline() function.

# r is the File Access Mode


# It means open file for reading
# fobj is the File Object
fobj = open("lovePoem.txt", "r")

emptyVar=False

# Grab the whole content of the text file


# by using read()
print("The content is read in line by line:\n")

line = fobj.readline() read only one line each time, NOT readlines()
if line=="":
print("Unfortunately, the file is empty! There is nothing can be
printed.")
emptyVar=True
else:
print(line, end="")

while line:
line = fobj.readline()
print(line, end="")
else:
if not emptyVar:
print("\n\n========================================")
print("All contents are printed already.")

# Close the file object when


# it is not in use
fobj.close()
P. 5 of 9

ch = input("")

If the text file has got data, the result would be like this:

Just in case the text file is empty, the output should behave like this:
P. 6 of 9

readlines() function
Sometimes, we can use readlines() to read all the lines of the text file and return
them as a list of strings.

This usage can be illustrated through the following python code, readlines.py:

# define an empty list in the first place


lineList = []

with open('lovePoem.txt', 'r') as fObj: #with as會自動關閉, 做埋try...except...

lineList = fObj.readlines()

counter = 1

print("Print out the lines by list:\n")


for line in lineList:
print("Item %d in lineList: " % counter, end="")
print(line, end="")
counter += 1

ch = input("")

The output of the above program is shown as follows:


P. 7 of 9

Further elaboration

Notice that the usage of with statement in creating file object. The with statement in
Python is used to simplify the management of common resources like file streams.

Through the usage of with statement, there is no need to call close() after finish
using the file. It is because the with statement itself already ensures proper
acquisition and release of resources.
P. 8 of 9

Write to Files
To open a file for writing, we set the second parameter of open( ) to "w" instead of
"r". To actually write the data into the file, we use method write() to handle it.

For the example below, we will write several sentences into a file called
writeDemo.txt.

Let’s finish the action by creating file writeDemo.py:

theFile = open("writeDemo.txt", "w")


theFile.write("My love for you will never end\nNo matter what happens in the future")
theFile.close()

ch = input("")

The output will be a text file called writeDemo.txt presented in Notepad:


P. 9 of 9

Classwork 1
Try to create a program (ReadAndWrite.py) that can read contents from file
lovePoem.txt and then:

1. Print the contents on screen as follows:

2. Write the contents to text file lovePoemCopy.txt.

You might also like