Python 6a Notes - Updated 1
Python 6a Notes - Updated 1
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.
You may grab its whole contents by writing the following Python script
(readWholeFile.py):
ch = input("")
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:
➢ 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.
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.
emptyVar=False
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.")
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:
➢ 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
➢ This simply prints a user-friendly message to indicate the file content will be
read line by line.
➢ 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 while line loop continues as long as line is not an empty string (""),
which indicates the end of the file.
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).
➢ The close() method is called to close the file and release any associated
system resources.
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:
counter = 1
ch = input("")
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:
➢ 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).
3. Initializing a Counter
counter = 1
➢ 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:
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.
import os
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("")
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.
➢ 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 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
➢ 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
➢ A message is printed to inform the user that the file has been created and the
content has been written to it.
➢ Example output:
Classwork 1
Try to create a program (ReadAndWrite.py) that can read contents from file
lovePoem.txt and then: