Chapter 10 – Files and Exceptions
- it’s important to learn how to work with files so your programs can analyze data efficiently
- necessary to learn how to handle errors
- exceptions – special objects Python creates to manage errors that arise while a program is running
- json module – allows you to save user data so it isn’t lost when your program stops running
- will learn how to handle exceptions to make your programs more robust to mistakes or malicious attacks
Reading from a file
- text files contain an incredible amount of data such as weather, traffic, socioeconomic, literary data, and more
- reading from a file is useful in data analysis, but is applicable when you want to analyze or modify information stored in a file
- can write a program that reads in the contents fo a text file and rewrites the file with formatting that allows a browser to display it
- when working with info in a text file, first you need to read the file into memory
Reading the contents of a file
- a file that contains pi to 30 decimal places, with 10 decimal places per line
pi_digits.txt
3.1415926535
8979323846
2643383279
- save this file as pi_digits.txt
- here’s a program that opens this file, reads it, and prints the contents of the file to the screen
file_reader.py
from pathlib import Path
path = Path(‘pi_digits.txt’)
contents = path.read_text()
print(contents)
- first, we need to tell Python the path to the file
- path – exact location of a file or folder on a system
- pathlib module – makes it easier to work with files and directories, regardless of OS
- library – module, like pathlib, that provides a specific functionality
- start by importing the Path class from pathlib
- next, we build a Path object representing the file pi_digits.txt and assign the variable path to it
- since the file is saved in the same directory as the .py file, the filename is all that Path needs to access it
- then we use read_text() method to read the entire contents of the file
- contents of the file are assigned to the variable contents
- when we print the value of contents, we see the entire contents of the text file
3.1415926535
8979323846
2643383279
- the only difference is the blank line at the end, which appears because read_text() returns an empty string at the end of the file
- use rstrip() to remove the extra blank line on the contents string
from pathlib import Path
path = Path(‘pi_digits.txt’)
contents = path.read_text()
contents = contents.rstrip()
print(contents)
- can strip the trailing newline character when we read the contents of the file, by applying the strip() method after calling read_text()
contents = path.read_text().rstrip()
- line tells Python to call the read_text() method on the file we’re working with
- then it applies the rstrip() method to the string that read_text() returns
- the cleaned-up string is assigned to the variable contents
- method chaining – this above approach
End of study session.