Python File Handling - CMPE 30032 Module 2

CalmFuchsia avatar
CalmFuchsia
·
·
Download

Start Quiz

Study Flashcards

20 Questions

What is the purpose of opening a file in Python before reading from or writing to it?

To access the resource and data stored within the file.

Text files store data in the form of characters.

True

Binary files store entire data in the form of ____, a group of 8 bits each.

bytes

What are the steps involved in file handling in Python according to the provided content?

Opening a file, reading or writing data, closing the file.

In Python, 'r' means ____ when opening a file for reading only.

read

Which function is used to read at most n characters from a file in Python?

read(n)

What does 'w' mean when opening a file in Python for writing?

write

How is a class defined in Python typically described?

A blueprint or code template for object creation

Structured programming paradigm is based on operations.

True

A ______ in Python is a user-defined data structure that binds the data members and methods into a single unit.

Class

What is the purpose of the 'try' block in exception handling?

The 'try' block is used to test a block of code for errors.

Match the following file permissions with their descriptions:

Read (r) = File can be 'looked at' by the program but not changed. Append (a) = File can be added to. Write (w) = Overwrites existing data, starting from the beginning of the file.

What is the purpose of class methods in Python?

To access or modify the class state.

Describe the characteristics of static methods in Python.

They are general utility methods that perform tasks in isolation and do not have access to class or instance variables.

What can constructors in Python be used for?

All of the above

Python uses the value of 'num' as a default value if the attribute 'self.num' is not defined in a ______ constructor.

default

Match the types of inheritance with their descriptions:

Single Inheritance = One class inherits from one parent class Multiple Inheritance = One class inherits from multiple parent classes Multilevel Inheritance = One class inherits from a parent class which in turn inherits from another class Hierarchical Inheritance = Multiple classes inherit from a single parent class

What is method overloading in Python?

Defining multiple methods in the same class with the same name but different parameters.

Explain the concept of method overriding in Python.

When a child class redefines a method from its superclass with the same name, parameters, and return type.

Method overriding allows a child class to redefine methods from the parent class.

True

Study Notes

File Handling in Python

  • File is a named location on disk to store related information, used to permanently store data in a non-volatile memory (e.g., hard disk).
  • File handling involves opening, reading, writing, appending, and closing a file.

File Types

  • There are two types of files: text files and binary files.
  • Text files store data in the form of characters, used to store characters or strings.
  • Binary files store entire data in the form of bytes, used to store text, images, audio, and video.

File Permissions

  • Read (r): file can be 'looked at' by the program, but not changed.
  • Append (a): file can be added to, file is created if it doesn't already exist.
  • Write (w): overwrites existing data, starting from the beginning of the file, file is created if it doesn't already exist.

Reading from a File

  • The algorithm: connect to and open the file, read the contents into a variable, output the variable, and close the file.
  • Read functions: read(n), readline(), readlines()
  • read(n): read at most n characters from the file, reads till end of file if it is negative or None.
  • readline(): read and return one line from the file, reads in at most n bytes if specified.
  • readlines(): read and return a list of lines from the file, reads in at most n bytes/characters if specified.

Writing & Appending to a File

  • Write to a file: open the file in write mode (w), use the write() function to write data, and close the file.
  • Append to a file: open the file in append mode (a), use the write() function to write data, and close the file.

Lab Exercises

  • Lab Exercise 4: write a Python program to read a text file, extract even and odd numbers, and write them to two separate files.
  • Lab Exercise 5:
    • 5.1: write a method to write multiple lines of text into a text file.
    • 5.2: write a method to create two separate text files containing the square of even integers and the cube of odd numbers found in a source text file.
    • 5.3: write a Python program to read a binary file, extract the name of the student with the highest GWA, and output the result.

String Manipulation

  • A string in Python is created by enclosing characters in quotes (either single quotes or double quotes)
  • Indexing: Python uses zero-based indexing, where the first character of a string has an index of 0
  • Accessing characters in a string: s[0], s[1], etc.
  • Slicing: s[3:5] returns a substring from index 3 to 5 (excluding 5)
  • String methods:
    • len(s): returns the length of the string
    • s.find("substring"): returns the index of the first occurrence of the substring
    • s.count("substring"): returns the number of occurrences of the substring
    • s.startswith("prefix"): returns True if the string starts with the prefix
    • s.endswith("suffix"): returns True if the string ends with the suffix
    • s.isdigit(): returns True if the string consists of digits only
    • s.isalpha(): returns True if the string consists of alphabets only
    • s.isalnum(): returns True if the string consists of alphanumeric characters only
    • s.title(): returns the string with the first character of each word capitalized
    • s.upper(): returns the string in uppercase
    • s.lower(): returns the string in lowercase
    • s.strip(): returns the string with leading and trailing whitespace removed
    • s.lstrip(): returns the string with leading whitespace removed
    • s.rstrip(): returns the string with trailing whitespace removed
    • s.replace("old", "new"): returns the string with all occurrences of "old" replaced with "new"

File Handling

  • File types:
    • Text files: used to store text data
    • Binary files: used to store binary data (such as images)
  • File operations:
    • Reading from a file: open("file.txt", "r")
    • Writing to a file: open("file.txt", "w")
    • Appending to a file: open("file.txt", "a")
  • File modes:
    • r: read mode
    • w: write mode
    • a: append mode
  • File permissions:
    • Read permission: allows reading from the file
    • Write permission: allows writing to the file
    • Execute permission: allows executing the file
  • Reading from a file:
    • read(n): reads at most n characters from the file
    • readline(): reads and returns one line from the file
    • readlines(): reads and returns a list of lines from the file
  • Writing to a file:
    • write(string): writes the string to the file
    • writelines(list): writes the list of strings to the file

Exception Handling

  • Types of exceptions:
    • Checked exceptions: occur at compile-time (e.g. syntax errors)
    • Unchecked exceptions: occur at runtime (e.g. division by zero)
  • Handling exceptions:
    • try block: contains the code that might raise an exception
    • except block: catches and handles the exception
    • else block: executes if no exception is raised
    • finally block: executes regardless of whether an exception is raised or not
  • Example of exception handling:
try:
    # code that might raise an exception
except ExceptionType:
    # handle the exception
else:
    # execute if no exception is raised
finally:
    # execute regardless of whether an exception is raised or not

Object-Oriented Programming

  • Programming paradigms:
    • Structured programming: focuses on procedures and functions
    • Object-oriented programming: focuses on objects and classes
  • Object-oriented programming concepts:
    • Classes: define the structure and behavior of objects
    • Objects: instances of classes
    • Inheritance: a class can inherit properties and behavior from another class
    • Polymorphism: objects of different classes can be treated as if they were of the same class
    • Encapsulation: hiding the implementation details of an object from the outside world
  • Class attributes:
    • Instance variables: attributes that belong to an instance of a class
    • Class variables: attributes that belong to a class
  • Class methods:
    • Instance methods: methods that belong to an instance of a class
    • Class methods: methods that belong to a class
    • Static methods: methods that can be called without creating an instance of a class
  • Constructors:
    • __init__: a special method that is called when an object is created
    • Default constructors: constructors that are called when no arguments are provided
    • Parameterized constructors: constructors that take arguments
  • Inheritance:
    • Single inheritance: a class inherits from one parent class
    • Multiple inheritance: a class inherits from multiple parent classes
    • Multilevel inheritance: a class inherits from a parent class that itself inherits from another parent class
    • Hybrid inheritance: a combination of multiple and multilevel inheritance
  • Method overriding: a child class provides a different implementation of a method that is already defined in its parent class

Quiz on reading, writing, and appending data to files in Python programming. Test your understanding of file handling concepts in Python.

Make Your Own Quizzes and Flashcards

Convert your notes into interactive study material.

Get started for free

More Quizzes Like This

Use Quizgecko on...
Browser
Browser