Chapter 10 documents and exceptions

Keywords: Python

1, Read data from file

1. Use the method read() to read the entire file

(1) Use the open() function to open a file. When calling the open() function, you need to pass a parameter to it. The name of the open file and python will find the specified document in the directory where the currently executed file is located. Note that if the file to be opened is not in the same directory as the currently running program file, you need to provide the path of the file (also divided into relative file path and absolute file path) so that Python can find it in a specific location of the system.

(2) Use the keyword with to let Python close the accessed file at the right time

file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as f:
    contents = f.read()

print(contents)

2. Use the for loop to read the file line by line

filename = 'pi_digits.txt'
with open(filename) as f:
    for line in f:
        print(line.rstrip())

3. Use the method readlines() to create a list containing the contents of each line of the file: when using the keyword with, the contents returned by the open() function are only available in the with code block. If you want to access the contents of the file outside the with block, you can use the method readlines() to read each line from the file and store it in a list

filename = 'pi_digits.txt'
with open(filename) as f:
    lines = f.readlines()

for line in lines:
    print(line.rstrip())

Note: when reading a file, Python interprets all text in it as strings. If you read a number and want to use it as a value, you need to convert it to an integer using the function int() or to a floating point number using the function float()

2, Use the write () method to write to the file

1. Write empty file: the file can be written by specifying another argument 'w' to open(); When the written file does not exist, the function open () automatically creates it.

(1) Similar mode arguments include read mode ('r '), write mode ('w'), additional mode ('a ') or read-write mode (R +). If the mode argument is omitted, Python will open the file in the default read-only mode.

(2) The function write() does not add a newline character at the end of the written text, so if you want to write multiple lines, you should add a newline character at the end of the string yourself \ n

2. Attach to file: when opening a file in write mode, Python will automatically empty the contents of the file object. Therefore, if you want to add content to the file instead of overwriting the original content, you can open the file in additional mode ('a ')

filename = 'programming.txt'

with open(filename, 'a') as f:
    f.write("I love Python!\n")
    f.write("What about you, my friend?\n")

3, Abnormal

1. Exception: exception is a special object used by Python to manage errors during program execution. Exceptions are handled using try except code blocks and else code blocks: the try code block contains only the code that may cause errors. The except code block tells Python how to handle such possible exceptions (or enter pass to silently fail). The else code block places the code to be run after the try code block is successfully executed

2. Handle the instance of ZeroDivisionError exception

print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")

While True:
    first_number = input("First number: ")
    if first_number == 'q':
        break
    second_number = input("Second number: ")
    if second_number == 'q':
        break
    try:
        answer = int(first_number)/int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)

3. Handle FileNotFoundError exception

4. Analyze text: the method split () can split the string into multiple parts with spaces as separators, and store these parts in a list

filename = 'alice.txt'

try:
    with open(filename, encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry, the filec{filename} does not exist.")
else:
    words = contents.split()
    num_words = len(words)
    print(f"The file {filename} has about {num_words} words.")

5. Combined with the for loop, multiple texts can be processed at the same time

def count_numbers():
    """Calculate how many words a text contains"""
    try:
    with open(filename, encoding='utf-8') as f:
        contents = f.read()
    except FileNotFoundError:
        print(f"Sorry, the file {filename} does not exist.")
    else:
        words = contents . split()
        num_words = len(words)
        print(f"The file {filename} has about {num_words} words.")

filenames = ['alice.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_numbers(filename)

4, Using the Json module to store data

1. Use json.dump() and json.load ():

(1) The json.dump() function can store data, which accepts two arguments: the data to be stored and the file object that can be used to store data

(2) The json.load() function loads data

import json

numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f:
    json.dump(numbers, f)

with open(filename) as f:
    numbers = json.load(f)
print(numbers)

2. Save and read user generated data

import json

filename = 'username.json'
try:
    with open(filename) as f:
        username = json.load(f)
except FileNotFoundError:
    username = input("Tell me your name: "
    with open(filename, 'w') as f:
        json.dump(username, f)
        print("We will remember it, next time")
else:
    print(f"Welcome back, {username}")

3. Refactoring: when the code can run normally, the process of improving it by dividing it into a series of functions to complete specific work is called refactoring. Refactoring can make the code clearer, easier to understand and easier to expand

Posted by VirtualOdin on Mon, 11 Oct 2021 20:30:02 -0700