0% found this document useful (0 votes)
12 views10 pages

Python Data Structures and File Handling

The document covers various programming concepts including data structures, file handling, and loop patterns in Python. It discusses the use of dataclasses, lists, and file operations, along with best practices for iterating over data. Additionally, it highlights the importance of managing resources by closing files and provides examples of directory navigation.

Uploaded by

wren.rust
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)
12 views10 pages

Python Data Structures and File Handling

The document covers various programming concepts including data structures, file handling, and loop patterns in Python. It discusses the use of dataclasses, lists, and file operations, along with best practices for iterating over data. Additionally, it highlights the importance of managing resources by closing files and provides examples of directory navigation.

Uploaded by

wren.rust
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

from dataclasses import dataclass

from bakery import assert_equal

@dataclass
class Food:
name: str
calories: int
cost: float

from drafter import *


from dataclasses import dataclass

@dataclass
class State:
name: str
age: int

@route
def index(state: State) -> Page:
return Page(state, Div(
TextBox("name", [Link]),
TextBox("age", [Link]),
Button("Change", "update")
))

@route
def update(state: State, name: str, age: int) -> Page:
[Link] = name
[Link] = age
return index(state)

start_server(State("Alice", 30))


animals = ["dog", "cat", "gerbil"]
# Indexing
print(animals[0])
print(animals[-1])
# Subscripting
print(animals[:2])
# Membership test
print("cat" in animals)
print("rabbit" in animals)
# Appending
[Link]("snake")
print(animals)

Primitives Types
●​ Boolean
●​ Integer
●​ Float
●​ String
●​ None

Introduction to Data Structures


●​ Lists: A new type that can hold multiple values of the same type.
●​ Dataclasses: A way of making new types that combine multiple bits of
different kinds of data into one bundle.
●​ You can use square brackets to slice a list:
○​ A single index will give you a single value from the list.
○​ A pair of subscripts will give you a list of elements from the list.
●​ You can test if two lists are equal (==) or not equal (!=) using the
equality operators.
●​ You cannot use the order comparison operators with lists (<, >, >=, <=).
●​ You can test if a value is inside of a list using the membership operator
(in).
●​ You can use the pop method to remove elements from the ends of lists
and the append method to add elements to the end of a list.

Mutability of Types
●​ Immutable: Strings, floats, integers, booleans
●​ Mutable: Lists, Dataclass

All the Patterns


●​ Count: Count how many elements are in a list
●​ Sum: Add up all the numbers in a list
●​ Accumulation: Combine elements into a single value
●​ Map: Modify all the elements of a list
●​ Filter: Remove elements from a list
●​ Find (First and Last): Get an element based on its value
●​ Take: Remove elements past a certain point in the list
●​ Minimum/Maximum: Get the highest or lowest value in a list

Summary
●​ We suggest several for loop patterns that can help you structure
programs that operate on lists of data:
○​ The count pattern is used to determine the number of elements in
a list.
○​ The sum pattern is used to add up a list of integers or floats.
○​ The accumulate pattern can be used to combine strings or
Booleans.
○​ The map pattern is used to transform elements of a list, either into
new values or possibly even new types of values.
○​ The filter pattern removes or keeps elements that match a
condition.
●​ Boolean accumulation comes in two varieties: the any pattern finds if
any values in a list of Booleans is True, and the all pattern finds if all
values in a list of Booleans are True.
●​ The map pattern can be dangerous because if you mistakenly append
to the list you are iterating over, the program might never end (it will loop
infinitely).
●​ The filter pattern is compatible with not only the map pattern but also the
sum and count patterns.
●​ A statement can be before, after, inside, or outside of a loop body.
●​ Loop patterns can be used inside of functions, just like any other
pattern.

Even More Loop Patterns


●​ Find: Get the first/last element that matches a condition.
●​ Take: Keep all the elements until they match a condition.
●​ Min/max: Find the highest or lowest element in a list.

Summary
●​ There are several other loop patterns, all of which involve conditionals:
○​ Find: Get the first/last element that matches a condition.
○​ Take: Get all the elements until they match a condition.
○​ Min/max: Find the highest or lowest element in a list.
●​ When the find pattern is used inside of a function and you are searching
for the first element that matches the condition, you can return early
from the function. But, if you are looking for the last element that
matches the condition, you should not return early.
●​ The min and max patterns are distinguished by the direction of the order
comparison operator used.
●​ Be careful to not use the min/max pattern on an empty list or it will
cause an IndexError.

grade_file = open('[Link]')
contents = grade_file.read()
grade_file.close()

grade_file = open('[Link]')
total = 0
count = 0
for line in grade_file:
grade = int([Link]())
total += grade
count += 1

grade_file.close()

Indexes vs. Values


1.​ Indexes allow more flexibility
2.​ Values require fewer operations
3.​ Values are less complex

Summary
●​ A for loop can iterate over the values in a list but can also iterate over
the indices in a list.
●​ Index iteration requires either the combination of the range and len
functions or the enumerate function.
○​ The len function consumes a list and produces an integer
representing the size of the list.
○​ The range function consumes an integer and produces a
sequence of integers from 0 to the given integer.
○​ The enumerate function consumes a list and produces a
sequence of pairs of indexes and values from a given list.
●​ You can change the value at a specific index of a list using assignment
syntax where the left-hand side is a list with an index.
●​ You can change all the values in a list using index iteration and
assignment statements.
●​ You can swap the values of two indexes using list unpacking and
multiple assignments.
●​ You can assign more than one variable at a time using multiple
assignments.
●​ Index iteration allows more flexibility and control while value iteration is
simpler and requires fewer operations.
●​ Lists and strings are both sequences, so you can index them and iterate
over them the same way.
●​ When you iterate over a string directly, the iteration variable will take on
each character, one at a time.
●​ You can use the split string method to turn a string into a list of strings.
○​ If you pass in no arguments, the string will be split on whitespace
characters.
○​ If you pass in a string value, the string will be split on that string.
●​ To iterate over chunks of a string, split the string and then use a for
loop to iterate over the resulting list of strings.

Directories
●​ Directories: A collection of files and directories
●​ Files: A sequence of data external to a program
●​ pwd: Print the current working directory.
●​ ls: List files in the current working directory.
●​ ls path: List files in the directory of the path.
●​ cd path: Change the current working directory to the given path

Reading Characters from a File


None

book_path = "[Link]"
book_file = open(book_path)

# Use the read() method to get the file as a string


book_text = book_file.read()
print(book_text)

Process File Character by Character


None

book_path = "[Link]"
book_file = open(book_path)

# Use the read() method to get the file as a string


book_text = book_file.read()
count = 0
for character in book_text:
count += 1
print(count)

Line-by-line File Iteration


None

book_path = "[Link]"
book_file = open(book_path)

for line in book_file:


print(line)

Line Endings
None

book_path = "[Link]"
book_file = open(book_path)

for line in book_file:


print([Link]())

Closing Files
None

book_path = "[Link]"
book_file = open(book_path)

print(book_file.read())

# This is critical!!!
book_file.close()

File Objects
●​ open function that takes a string path and returns an open file object
●​ close method of file objects that frees up the resource
●​ read method of file objects that returns the contents of the file as a
string
●​ for loop iteration over the file object as a sequence of strings
(separated by newlines)

Summary
●​ Data stored in files can be accessed through a programming language
like Python.
●​ You can call the open function in Python with a string filename to get a
file object.
●​ A file object has two operations that you can use to access the actual
data in the file:
○​ The .read() method returns the contents of the file as a string
value.
○​ You can use a for loop to iterate through a file as a sequence of
strings, separating the file based on its new lines.
●​ The .read() method gives you a string, so you can iterate through the
string character by character just like any other string.
●​ The line-by-line iteration approach still includes the new line at the end
of a line, so usually you will use the .strip() method to remove the
extra whitespace from the end of each line.
●​ When you are done working with a file, you should call the .close()
method to indicate that the file is no longer necessary and to free up
resources.

Moving between directories


None

# Absolute path:
# Move to specific folder anywhere in your file
system
$> cd /c/Users/acbart/projects

# Relative path:
# Move to folder in current directory
$> cd pythonmisc/

# Move up a level
$> cd ../
Text Version
None

root/
School work/
[Link]
[Link]
Photos/
[Link]
Me_irl.jpg
Python/
[Link]
[Link]

Absolute Path
None

/root/python/[Link]
/home/acbart/python/[Link]
C:/Users/acbart/python/[Link]
C:\\Users\\acbart\\python\\[Link]

Common questions

Powered by AI

Index iteration offers more flexibility and control because you can directly access and modify elements at specific positions. It allows operations like swapping values, while value iteration is simpler and requires fewer operations since it directly deals with the list's values.

To read a file character by character in Python, open the file using the 'open' function and the 'read' method to load the contents as a string. Then, use a for loop to iterate over each character in the string for further processing. This method lets you handle specific character operations directly.

Absolute paths specify a complete path from the root directory to a particular file or folder, while relative paths specify a location relative to the current working directory. Absolute paths provide a fixed reference that doesn’t change based on the current location, whereas relative paths can be shorter and more flexible within a consistent directory structure.

While equality operators (==, !=) can be used to compare lists, the order comparison operators (<, >, <=, >=) are not supported between lists. This restriction helps avoid ambiguous comparisons that do not have a clear intuitive meaning for ordered collections.

To modify all elements in a list through index iteration, use a for loop in combination with the range and len functions to iterate over indices. This allows direct access to each position in the list, where you can apply an assignment statement to modify the element at that index.

The map pattern is useful because it allows the transformation of elements in a list into new values or even new types. However, it can be hazardous because if you mistakenly append elements to the list you are iterating over, it might cause an infinite loop, potentially leading the program to never end.

After finishing file operations in Python, it is crucial to call the .close() method on the file object. This releases resources and indicates that the file is no longer needed, preventing potential leaks and ensuring that the file is properly handled by the operating system.

A dataclass offers a structured and concise way to bundle related data together with automatic generation of special methods like __init__(), __repr__(), and __eq__(). It can enhance code readability and maintainability compared to a regular class, where you manually code these methods, or a dictionary, which lacks type safety and structural clarity.

Caution is needed when applying the min/max pattern to an empty list as it can cause an IndexError. It’s essential to ensure the list has elements before attempting to find the minimum or maximum to prevent errors.

Boolean accumulation patterns, such as the any and all patterns, efficiently determine conditions across a list of Booleans. 'Any' checks if at least one element meets the condition, while 'all' checks if all elements do. They are beneficial because they condense complex logical checks into a single, more readable operation.

You might also like