Podcast
Questions and Answers
Why is file handling an important concept in programming?
Why is file handling an important concept in programming?
- It enhances the graphical user interface of applications.
- It automatically optimizes program execution speed.
- It enables programs to store and retrieve data from files on disk. (correct)
- It allows programs to directly manipulate hardware components.
When a file is opened in 'write' mode ('w') in Python, what happens to the existing content of the file?
When a file is opened in 'write' mode ('w') in Python, what happens to the existing content of the file?
- An error is raised if the file already exists.
- The existing content is deleted, and the file is overwritten with new data. (correct)
- The file is opened in read-only mode, preventing any changes.
- The existing content is preserved, and new data is appended to the end.
What is the primary difference between a text file and a binary file?
What is the primary difference between a text file and a binary file?
- Text files are faster to read and write compared to binary files.
- Text files can only store alphabetic characters, while binary files can store any type of data.
- Text files store information in ASCII or Unicode, while binary files store information in the same format as in memory. (correct)
- Text files do not require a file handle, while binary files do.
Which of the following is the correct way to associate an external file with a program object?
Which of the following is the correct way to associate an external file with a program object?
What is the purpose of the finally
block in exception handling?
What is the purpose of the finally
block in exception handling?
What is the significance of the 'EOL' character in text files?
What is the significance of the 'EOL' character in text files?
In Python, what happens if you try to open a file that does not exist in 'read only' mode ('r')?
In Python, what happens if you try to open a file that does not exist in 'read only' mode ('r')?
Which file access mode in Python allows both reading and writing to a file?
Which file access mode in Python allows both reading and writing to a file?
What will be the likely outcome if a Python program attempts to divide a number by zero?
What will be the likely outcome if a Python program attempts to divide a number by zero?
What is the main purpose of the rstrip()
method when processing files?
What is the main purpose of the rstrip()
method when processing files?
In the context of file handling, what does it mean to 'iterate through a sequence'?
In the context of file handling, what does it mean to 'iterate through a sequence'?
Which statement regarding exception handling in Python is correct?
Which statement regarding exception handling in Python is correct?
What is the purpose of the continue
statement when searching through a file word by word?
What is the purpose of the continue
statement when searching through a file word by word?
In Python, how can you determine if a specific substring exists within a line read from a file?
In Python, how can you determine if a specific substring exists within a line read from a file?
When handling exceptions, what happens if an exception is raised within the try
block and there is no matching except
block to handle that particular exception?
When handling exceptions, what happens if an exception is raised within the try
block and there is no matching except
block to handle that particular exception?
Which of the following is a characteristic of a logical error in Python?
Which of the following is a characteristic of a logical error in Python?
What is the most appropriate use case for the file access mode 'x'?
What is the most appropriate use case for the file access mode 'x'?
Which of the following shows correct syntax of writing a string to a file, given the file handle called newFile
?
Which of the following shows correct syntax of writing a string to a file, given the file handle called newFile
?
What would happen if you were to run:
existingFile = open('notAFile.txt', 'r')
What would happen if you were to run:
existingFile = open('notAFile.txt', 'r')
The program crashes with message: TypeError: unsupported operand type(s) for +: 'int' and 'str'
. What type of error is this?
The program crashes with message: TypeError: unsupported operand type(s) for +: 'int' and 'str'
. What type of error is this?
Why do you have to .close()
a file?
Why do you have to .close()
a file?
When is the code in a finally
block executed?
When is the code in a finally
block executed?
What does logging exceptions do?
What does logging exceptions do?
What will the following code print if user_input=0
?
try:
result = 10 / user_input
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input provided.")
What will the following code print if user_input=0
?
try:
result = 10 / user_input
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input provided.")
What is the purpose of opening a file in append mode ('a')?
What is the purpose of opening a file in append mode ('a')?
What is a key advantage of using binary files over text files?
What is a key advantage of using binary files over text files?
If a file is opened without specifying a mode, what is the default file access mode?
If a file is opened without specifying a mode, what is the default file access mode?
Which type of error is caused by violating the grammatical rules of a programming language?
Which type of error is caused by violating the grammatical rules of a programming language?
Which code snippet will reliably count the number of lines in names.txt
?
Which code snippet will reliably count the number of lines in names.txt
?
What is the difference between .read()
, .readline()
, and .readlines()
?
What is the difference between .read()
, .readline()
, and .readlines()
?
With the file some_artists.txt
containing:
Van Gogh
Monet
Rembrandt
Da Vinci
What will the following code output?
file = open('some_artists.txt')
for artist in file:
if 'V' in artist:
print(artist.strip())
With the file some_artists.txt
containing:
Van Gogh
Monet
Rembrandt
Da Vinci
What will the following code output?
file = open('some_artists.txt')
for artist in file:
if 'V' in artist:
print(artist.strip())
What is the primary purpose of using the logging
module in Python?
What is the primary purpose of using the logging
module in Python?
Given the built-in exceptions, which can be resolved and handled? (Select all that apply)
Given the built-in exceptions, which can be resolved and handled? (Select all that apply)
What is the correct way to define a method that catches all errors derived directly from the base Exception class?
What is the correct way to define a method that catches all errors derived directly from the base Exception class?
Flashcards
File Handling
File Handling
A mechanism to read data from or write data to disk files in a Python program.
Text File
Text File
Stores information in ASCII or UNICODE characters.
Binary File
Binary File
Stores information in the same format as in memory, without newline delimiters; faster for programs to process.
File I/O
File I/O
Signup and view all the flashcards
Opening a file
Opening a file
Signup and view all the flashcards
File handle
File handle
Signup and view all the flashcards
Open mode 'w'
Open mode 'w'
Signup and view all the flashcards
Open mode 'a'
Open mode 'a'
Signup and view all the flashcards
Open mode 'r'
Open mode 'r'
Signup and view all the flashcards
EOL (End of Line)
EOL (End of Line)
Signup and view all the flashcards
Iterating through a file
Iterating through a file
Signup and view all the flashcards
Types of Errors
Types of Errors
Signup and view all the flashcards
Syntax Errors
Syntax Errors
Signup and view all the flashcards
Runtime Errors (Exceptions)
Runtime Errors (Exceptions)
Signup and view all the flashcards
Logical Errors
Logical Errors
Signup and view all the flashcards
Exception
Exception
Signup and view all the flashcards
Try block
Try block
Signup and view all the flashcards
Except block
Except block
Signup and view all the flashcards
Finally block
Finally block
Signup and view all the flashcards
ZeroDivisionError
ZeroDivisionError
Signup and view all the flashcards
NameError
NameError
Signup and view all the flashcards
IndentationError
IndentationError
Signup and view all the flashcards
IOError
IOError
Signup and view all the flashcards
EOFError
EOFError
Signup and view all the flashcards
Logging
Logging
Signup and view all the flashcards
Study Notes
Topic 11: File and Exception Handling
- Covers Python programming, specifically file and exception handling
Topic Learning Outcomes
- Understand opening files with different modes
- Demonstrate an understanding of file manipulation
- Implement reading from and writing to text files
Contents Overview
- Creating a text file
- Opening files in different modes
- Writing data into a file
- Reading data from a file
- Searching through a file
- Exception handling
Introduction to File Handling
- File handling is a mechanism to read data from or write data to disk files in Python programs.
- Input typically comes from the keyboard, output displayed on the monitor.
- Without file handling, data isn't stored permanently
- File handling lets one store data entered through a program permanently in a disk file.
Advantages of Files
- Large amounts of data storage is possible
- Data is stored permanently
- Data can be easily shared across various programs
- Updates to data are easily implemented
Data Files Overview
- Data files contain data for specific applications, and are intended for later use
- Data files may be stored in two formats: text files and binary files
Text Files
- Text files store information in ASCII or Unicode characters
- Everything is stored as a character
- Text files are terminated by a special character called EOL (End Of Line)
- An EOL error means the Python interpreter reached the end of a line while scanning a string literal
- String literals or constants should be enclosed in single or double quotes
Binary files
- Binary files store information in the same format as it is stored in memory
- Binary files have no delimiter for newline characters
- Programs can read and write binary faster / easier than text
- Data in binary files cannot be directly read and requires a Python program
File I/O
- One can read information from a file or write information to a file via File I/O
- File I/O refers to "input/output"
- Python contains built-in functions to simplify file I/O operations
Steps in Data File Handling
- Opening a file involves associating an external file with a program object
- Reading or writing to a file allows manipulation of the file object
- Closing a file should be done after operations are complete
Opening Files
- Before reading a file's contents, Python needs to know which file the operations will apply to
- The process is done via the
open()
function open()
returns a "file handle," which is a variable for performing operations on the file- Opening a file is like navigating to
"File -> Open"
in a word processor
File Opening Modes and Syntax
- Files can be opened for reading, writing, or appending
file = open(filename)
is the syntaxfile = open(filename, mode)
can define the mode- The default mode for opening a file is read
Syntax for Open() - Details
myFile = open(FILE_NAME, ACCESS_MODE)
- FILE_NAME is a string containing the name of the file you want to access
- Examples:
"input.txt"
,"numbers.dat"
,"roster.txt"
- ACCESS_MODE is an optional argument string that determines the mode files open in
-
"r"
: open for reading -"w"
: open for writing -"a"
: open for appending
File Access Modes Table
w
: Opens in write-only mode and creates the file if it doesn't exist, overwrites if the file existsr
: Opens in read-only mode, file I/O error if the file doesn't exista
: Opens in append mode to add new data at the end, creates the file if it doesn't existw+
: Opens a file in both read/write mode, overwrites the file if it exists already or creates a new file if it does not existr+
: Opens a file in both read and write mode, and raises an i/o error if the file does not exista+
: Opens in append and read mode, can read and write to the file, creates the file if it doesn't exist, adds text to the existing datax
: Exclusive creation mode; opens a file for writing only if it doesn’t already exist
Examples of Using open()
testFile = open("scores.txt")
dataIn = open("old_stats.dat")
dataOut = open("stats.dat", "w")
- The
scores.txt
file contains lines of floating point numbers
Writing Files
name = open("filename", "w")
: Opens the file to be able to write on it, as well as delete all previous contentname = open("filename", "a")
: Opens the file to append to it, i.e. add data behind all previous dataname.write(str)
: Writes a given string to the filename.close()
: Closes the file once writing is complete
Handling Missing Files
- Trying to open a file that doesn't exist causes a
FileNotFoundError
exception - e.g.
No such file or directory: 'fileName.txt'
File Processing
- A text file could be considered a sequence of lines
- Text files have newline characters at the end of each line
File Handle as a Sequence
- A file handle opened for reading can be treated as a sequence of strings
- Each line in the file is a string in this sequence.
- The
for
statement is used to iterate through a sequence
Counting Lines
- Open a file in read-only mode
- Use a
for
loop to read each line - Count the lines and get a total count
Searching Through a File
- Put an if statement in a
for
loop to print out lines that meet certain criteria
Searching Through a File (Fixed)
- The
rstrip()
function, a string library function, strips white space from the string's right-hand side - Newlines are considered "white space" and are stripped
Skipping with Continue
- The
continue
statement helps skip a line
Using in
to Select Lines
- Searches a string anywhere in the line and uses this search as our selection criteria
Prompt for File Name
- Take a filename as input
- Count the number of lines that meet a certain criteria
- Print the filename alongside the number of lines
Bad File Names
- A try...except statement can handle cases where a file cannot be opened
- The except statement can print an error message and exit the program
Using File Objects to Read Files
myFile = open("myStuff.txt")
- The line of code opens the "myStuff.txt" file in reading mode, and assigns the opened file to the
myFile
variable myFile
is a variable of type file object- Once the file is open, reading of it may begin
3 Ways to Read Files
name = open("filename")
opens the file, returning a file objectname.read()
: Reads the entire file, returning it as a stringname.readline()
: Reads the next line from the file as a stringname.readlines()
: Reads all the file content, returning it as a list of lines.- Lines may also be read with a
for
loop
Closing Files
f.close()
closes the file
Exception handling
- Ensures, if an error happens we handle it instead of crashing the program
Introduction to Exception Handling
- Python programs often encounter errors
- Errors caused by not following proper language structure are syntax or parsing errors
- Errors can also occur at runtime, also known as exceptions
FileNotFoundError
occurs if Python can't find the file,ZeroDivisionError
if dividing by zero- If Python creates an exception object but isn't handled, the error will print along with details as to why the error occurred
Python Errors and Exceptions
- Encountering errors and exceptions can make coding frustrating
- Knowing about different types of errors helps
- Errors are classified into syntax errors, runtime errors or logical errors
Syntax Errors (Compile Time)
- Syntax errors result from not following proper language syntax
- Syntax errors happen when programming language rules are misused
- These are detected when the code is compiled
Runtime Errors (Exceptions)
- Exceptions happen when an program is run
- Caused by illegal operations, which may not be realized until running
- A syntactically correct program may cause Python to raise an exception
- e.g., trying to open nonexistent or corrupted files
- e.g., dividing a number by zero (ZeroDivisionError)
Logical Errors
- Logical errors produce incorrect results even when the program runs without crashing
- Logical errors result from a mistake in the program's logic
- Logical errors wont generate error messages because no syntax or runtime errors are encountered
Exceptions Defined
- Even if a statement or expression has proper syntax, it may cause an error at execution time
- Errors detected during execution are called exceptions
- An exception is an event disrupting the normal flow of program instructions
Error Examples
- Dividing by zero: results in ZeroDivisionError
- Referring to an undefined variable: results in a NameError
- Performing an operation on incompatible data types: results in a TypeError
Python Exception Handling
- When a Python script can't cope with a situation, it raises an exception.
- A Python script has to handle the exception immediately, or will terminate
- Python exception handling uses:
- The
try
block: Tests a block of code for errors. - The
except
block: Handles errors. - The
finally
block: Executed code regardless of try/except block outcomes - When an error occurs, Python normally stops and generates an error message
Python Exception Handling – Try Block
- Exceptions can be handled with the
try
statement - If the
try
block raises an error, theexcept
block will be executed - Without the
try
block, the program will crash and raise an error
Exception Handling - Example
- Perform division and understand exception handling
- If an exception occurs,
"Exception handled"
prints instead of error
The try
/ except
Structure
- Surround a dangerous section of code with
try
andexcept
- If the
try
block works, theexcept
block is skipped - If the code in the
try
block fails, Python jumps to theexcept
block - A
try
statement can have multipleexcept
blocks to handle different exceptions
Try with Different Exceptions
- Include multiple exceptions in the try and except block to give tailored responses
The try / except Structure - Continued
- Multiple exceptions are put into a single
except
block using parentheses - This means the
except
block can handle multiple exceptions
More Examples
Try… Finally
- A
finally
block can be used with atry
block - the code placed in the
finally
block is executed no matter Exception is caused or caught - Cannot use
except
clause andfinally
clause together with atry
block - It is also not possible to use
else
clause andfinally
together withtry
block.
Try-Finally Example
- If there is an error trying to write the file, the code in the
finally
clause will be executed
Built-in Exceptions
ZeroDivisionError
: Raised when division or modulo by zero takes place for all numeric types.NameError
: Raised when name of keywords, identifiers, etc are wrongIndentationError
: Raised when indentation is not properly givenIOError
: Raised when an input/output operation fails, such asprint
oropen()
functionEOFError
: Raised when there is no input fromraw_input()
orinput()
and end of file reached
Logging Exceptions
- Logging tracks events that happen when software runs
- Logging is important for developing, debugging, and running programs
- Log exceptions with
logging.exception()
method - It logs a message with ERROR level
- Arguments are interpreted for
debug()
- The method should only be called from an exception handler
Logging the Exceptions
- Logging an exception in Python with an error can be done in the logging.exception() method.
- Exception info is added to the logging message
- Only call
logging.exception()
from an exception handler
Summary
- Creating a text file
- Opening files in different modes
- Writing data into a file
- Reading from a file
- Searching through a file
- Exception handling
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.