0% found this document useful (0 votes)
3 views20 pages

Python 6a Notes - Updated 1

The document provides a comprehensive guide on file handling in Python, covering reading from files using read(), readline(), and readlines() functions, as well as writing to files with the write() function. It includes detailed explanations and code examples for each method, demonstrating how to open, read, and write files while ensuring proper resource management. Additionally, it emphasizes the importance of checking for existing files before writing to avoid unintentional data loss.

Uploaded by

gigicho0815
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)
3 views20 pages

Python 6a Notes - Updated 1

The document provides a comprehensive guide on file handling in Python, covering reading from files using read(), readline(), and readlines() functions, as well as writing to files with the write() function. It includes detailed explanations and code examples for each method, demonstrating how to open, read, and write files while ensuring proper resource management. Additionally, it emphasizes the importance of checking for existing files before writing to avoid unintentional data loss.

Uploaded by

gigicho0815
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/ 20

P.

1 of 20

Contents

Files ................................................................................................................................ 2
Read from Files....................................................................................................... 2
read() function ............................................................................................... 2
Elaboration of readWholeFile.py ........................................................... 4
readline() function ......................................................................................... 5
Elaboration of readline.py...................................................................... 7
readlines() function ...................................................................................... 10
Elaboration of readlines.py .................................................................. 11
Write to Files ........................................................................................................ 14
Elaboration of writeDemo2.py..................................................................... 16
Classwork 1 .......................................................................................................... 20
P. 2 of 20

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:
P. 3 of 20

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()

ch = input("")

The output should be:


P. 4 of 20

Elaboration of readWholeFile.py

This Python program demonstrates how to open, read, and close a text file. Below is
an elaboration of each part of the code:

1. Opening the File


fobj = open("lovePoem.txt", "r")

➢ The open() function is used to open a file.


➢ "lovePoem.txt": This is the name of the text file that you want to open.
➢ "r": This is the file mode. The "r" mode stands for "read mode." It means
the file will be opened for reading only. You cannot write or modify the file in
this mode.
➢ fobj: This is the file object created by the open() function. It allows you to
interact with the file (e.g., to read its contents).

2. Reading the File Content


print(fobj.read())

➢ The read() method reads the entire content of the file as a single string.
➢ fobj.read(): This reads all the text in the file lovePoem.txt.
➢ print(): This outputs the content of the file to the console for the user to
see.

3. Closing the File


fobj.close()

➢ The close() method is used to close the file object.


➢ When a file is opened, it uses system resources. Closing the file releases these
resources.
➢ It is a good practice to always close a file after you are done using it. If a file is
not closed properly, it can lead to issues like data corruption or resource
leaks.
P. 5 of 20

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()
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. 6 of 20

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. 7 of 20

Elaboration of readline.py

This Python program demonstrates how to read a text file line by line and handle
cases where the file is empty. Below is an elaboration on each part of the code:

1. Opening the File


fobj = open("lovePoem.txt", "r")

➢ The open() function opens the file lovePoem.txt in read mode ("r").
➢ fobj is the file object that allows interaction with the file (e.g., reading its
contents).
➢ If the file does not exist or there is an issue opening it, an error will be raised.

2. Initializing a Variable
emptyVar = False

➢ emptyVar is a flag variable used to track whether the file is empty.


➢ Initially, it is set to False (indicating the file is not empty).

3. Reading and Printing the File Line by Line


a. Printing Information
print("The content is read in line by line:\n")

➢ This simply prints a user-friendly message to indicate the file content will be
read line by line.

b. Reading the First Line


line = fobj.readline()

➢ The readline() method reads the first line of the file.


➢ If the file is empty, readline() will return an empty string ("").
P. 8 of 20

4. Handling the Case of an Empty File


if line == "":
print("Unfortunately, the file is empty! There is nothing
can be printed.")
emptyVar = True
else:
print(line, end="")

➢ If the first line is an empty string (""), it means the file is empty.
✓ A message is displayed:
"Unfortunately, the file is empty! There is nothing
can be printed."

✓ The emptyVar flag is set to True to indicate the file is empty.

➢ If the file is not empty, the first line is printed.


✓ end="" prevents adding an extra newline, as line already contains a
newline character at the end.

5. Reading the Rest of the File


while line:
line = fobj.readline()
print(line, end="")

➢ The while line loop continues as long as line is not an empty string (""),
which indicates the end of the file.

➢ Inside the loop:


✓ fobj.readline() reads the next line from the file.
✓ print(line, end="") prints the line to the console without
adding an extra newline.

➢ When the end of the file is reached, fobj.readline() returns an empty


string (""), causing the loop to exit.
P. 9 of 20

6. Final Message After Reading the File


else:
if not emptyVar:

print("\n\n========================================")
print("All contents are printed already.")

➢ The else block of the while loop is executed when the loop terminates (i.e.,
when all lines have been read).

➢ If emptyVar is still False (indicating the file was not empty):


✓ A separator ("========================================") is
printed.
✓ A message indicating that all contents have been printed is displayed.

7. Closing the File


fobj.close()

➢ The close() method is called to close the file and release any associated
system resources.

➢ It is important to close the file after use to avoid resource leaks.


P. 10 of 20

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:


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.strip())
counter += 1

ch = input("")

The output of the above program is shown as follows:


P. 11 of 20

Elaboration of readlines.py

This Python program reads all the lines of a file into a list and then iterates over the
list to print each line, with unnecessary whitespace removed. Let's break it down
step by step:

1. Defining an Empty List


lineList = []

➢ An empty list named lineList is initialized.


➢ This list will later hold all the lines of the file as individual strings.

2. Reading the File into a List


with open('lovePoem.txt', 'r') as fObj:
lineList = fObj.readlines()

➢ The with statement is used to open the file lovePoem.txt in read mode ('r').
✓ This ensures that the file is automatically closed after the block is
executed, even if an error occurs.

➢ The readlines() method reads all lines of the file and stores them in the
list lineList.
✓ Each line in the file becomes a string element in the list, including any
leading or trailing whitespace (like spaces or newline characters).

For example, if lovePoem.txt contains:

If you know my true hearted


How come you never get impressed
Whoelse can reckon you never responded

Then lineList will look like this:


[
"If you know my true hearted, \n",
"How come you never get impressed, \n",
" Whoelse can reckon you never responded, \n"
]
P. 12 of 20

3. Initializing a Counter
counter = 1

➢ A variable counter is initialized to 1.


➢ This will be used to display the line number (or item number) when printing
each line.

4. Printing the Lines from the List


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

➢ A message is printed to indicate that the lines will be displayed.

Iterating Over the List


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

➢ for line in lineList:


✓ A for loop is used to iterate over each element (line) in the lineList.
✓ Each line is a string representing one line of the file, including its
original formatting (like leading/trailing whitespace and newline
characters).

➢ print("Item %d in lineList: " % counter, end="")


✓ This prints the current item number (counter) in lineList along with
the label "Item %d in lineList: ".
✓ The %d is a placeholder for the integer value of counter.
✓ end="" prevents the print() function from adding a newline after
this part of the output.

➢ print(line.strip())
✓ The strip() method is called on each line to remove any leading or
trailing whitespace, including spaces and newline characters (\n).
✓ This ensures that only the meaningful text of the line is printed.
P. 13 of 20

➢ counter += 1
✓ After printing each line, the counter is incremented by 1 to reflect the
next line number.

Example Output
Assume the file lovePoem.txt contains:

If you know my true hearted


How come you never get impressed
Whoelse can reckon you never responded

The output will be:

Item 1 in lineList: If you know my true hearted


Item 2 in lineList: How come you never get impressed
Item 3 in lineList: Whoelse can reckon you never responded

Notice that the trailing spaces and newline characters from the original file are
removed because of the strip() method.
P. 14 of 20

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
writeDemo2.txt.

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

import os

# Specify the file name


file_name = "writeDemo2.txt"

# Check if the file already exists


if os.path.exists(file_name):
print("The file %s already exists. The program will not overwrite or create
the file again." %file_name)
else:
# Open the file in write mode
with open(file_name, "w") as fobj:
# Write some content to the file
fobj.write("Roses are red,\n")
fobj.write("Violets are blue,\n")
fobj.write("Python is fun,\n")
fobj.write("And so are you.\n")

theContent = "Roses are red,\n" + \


"Violets are blue,\n" + \
"Python is fun,\n" + \
"And so are you.\n"

print(theContent)
P. 15 of 20

print("The file %s has been created and the above contents have been written
to it." %file_name)

ch = input("")

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

Notice that the console should show the following figure if the contents are written
to file writeDemo2.txt successfully.

Just in case the mentioned text file already exists, the following figure will be
displayed for user reference.
P. 16 of 20

Elaboration of writeDemo2.py
This code provides a simple example of safely creating or writing to a file while
avoiding overwriting existing files.

1. Importing the os Module


import os

➢ The os module in Python provides a way to interact with the operating


system.
➢ Using this module, you can handle files and directories, check if they exist, get
file metadata, and more.
➢ In this code, the os.path.exists() function is used to check if a specific
file already exists.

2. Specifying the File Name


file_name = "writeDemo2.txt"

➢ A variable file_name is assigned the string "writeDemo2.txt".


➢ This represents the name of the file to be checked, created, or written to.
P. 17 of 20

3. Checking if the File Exists


if os.path.exists(file_name):
print("The file %s already exists. The program will not
overwrite or create the file again." % file_name)

➢ os.path.exists(file_name):
✓ Checks if a file with the name "writeDemo2.txt" exists in the
current working directory.
✓ Returns True if the file exists, otherwise False.

➢ If the file exists:


✓ A message is printed using % formatting:

print("The file %s already exists. The program will not


overwrite or create the file again." % file_name)

✓ Example output (if the file exists):

The file writeDemo2.txt already exists. The program will not


overwrite or create the file again.

4. Creating and Writing to the File


else:
# Open the file in write mode
with open(file_name, "w") as fobj:

➢ If the file does not exist, the program enters the else block.
➢ The file is opened in write mode ("w") using the open() function:
✓If the file does not exist, it is created.
✓ If the file already exists, its contents would normally be overwritten
(though this doesn't happen here because of the if check).
➢ The with statement ensures proper file handling:
✓ Automatically closes the file after the block of code is executed.
✓ Prevents file corruption in case of exceptions.
P. 18 of 20

5. Writing Content to the File


fobj.write("Roses are red,\n")
fobj.write("Violets are blue,\n")
fobj.write("Python is fun,\n")
fobj.write("And so are you.\n")

➢ The write() method is used to write text to the file.


➢ Each line ends with \n, which adds a newline character, ensuring the content
is written on separate lines.
➢ The content written to the file is:

Roses are red,


Violets are blue,
Python is fun,
And so are you.

6. Storing the Content in a String


theContent = "Roses are red,\n" + \
"Violets are blue,\n" + \
"Python is fun,\n" + \
"And so are you.\n"

➢ The same content that was written to the file is stored in a variable
theContent.
➢ The + operator concatenates strings, and \ allows breaking the line for better
readability.
P. 19 of 20

7. Printing the Content


print(theContent)

➢ This prints the content stored in theContent to the console.


➢ Example output:

Roses are red,


Violets are blue,
Python is fun,
And so are you.

8. Informing the User About File Creation


print("The file %s has been created and the above contents
have been written to it." % file_name)

➢ A message is printed to inform the user that the file has been created and the
content has been written to it.
➢ Example output:

The file writeDemo2.txt has been created and the above


contents have been written to it.
P. 20 of 20

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