File and exception

File and exception

Read data from file

To use the information in the text file, you first need to read the information into memory

Read entire file

pi_digits.txt

3.1415926535
   8979323846
   2643383279

file_reader.py

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())

The function open() returns an object representing a file

Keyword with closes the file after it is no longer needed to access it

You can also call open() and close () to open and close the file. However, if the program has a Bug and the close () statement is not executed, the file will not be closed, which may lead to data loss or damage. If you call close() too early, you will find that it has been closed when you need to use the file, which will lead to more errors.

The method read() reads all the contents of the file and stores it as a long string in the variable contents; When the end of the file is reached, an empty string is returned and displayed as an empty line, which can be deleted by the restrict () method

File path

Will 'pi_ When 'digits. TXT' is passed to open(), Python will look for the file in the directory where the currently executed file is located

Open a file using a relative file path: Python looks in the directory relative to the currently running program

with open('text_files\filename.txt') as file_object:

Use absolute path: you can read files anywhere in the system

file_path = 'C:\Users\19405\Desktop\filename.txt'

with open(file_path ) as file_object:

Absolute paths are usually longer than relative paths, so it helps to store them in a variable and pass it to open()

Read line by line

file_path = 'pi_digits.txt'
with open(file_path) as file_object:
    for line in file_object:
        print(line)

In the file, there is an invisible newline character at the end of each line, and a newline character will be added to the print() statement, so there will be two newlines at the end of each output line: one from the file and one from print()

Eliminate extra blank lines:

print(line.rstrip())

Create a list containing the contents of each line of the file

When using the keyword with, the file object returned by open() is only available within the with code block

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

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

The method readlines() reads each line from the file and stores it in another list

Use the contents of the file

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.strip()

print(pi_string)
print(len(pi_string))

When reading a text file, Python interprets all text in it as strings; If you read a number and want to use it as a numeric value, you must convert it to an integer or floating point number using the function int() or float()

A large file containing one million bits

filename = 'pi_million_digits.txt'

--snip--

print(pi_string[:52] + '...')
print(len(pi_string))

Does PI include your birthday

birthday = input("Enter your birthday, in the form mmddyy: ")
if birthday in pi_string:
    print("Your birthday appears in the first million digits of pi")
else:
    print("No")

write file

One of the easiest ways to save data

Write empty file

filename = 'programming.txt'

with open(filename, 'w') as file_object:
    file_object.write("I love programming.")

The second argument to open():

'r': read mode

'w': write mode: if the file does not exist, it will be created automatically; If the file already exists, empty it

'a': additional mode

'r +': read and write modes

Python can only write strings to text files

Write multiple lines

The function write() does not add a newline character to the end of the text you write, so you need to specify a newline character when writing multiple lines

filename = 'programming.txt'

with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")

Attach to file

Add content to the file instead of overwriting the original content

Additional mode

filename = 'programming.txt'

with open(filename, 'a') as file_object:
    file_object.write("I also love finding meaning in large datasets.\n")
    file_object.write("I love creating new games.\n")

abnormal

Python uses special objects called exceptions to manage errors that occur during program execution

Whenever an error occurs, an exception object is created

Exceptions are handled using the try exception code block. With this module, the program will continue to run even if an exception occurs

Handling ZeroDivisionError exception

print(5/0)

The program fails to run, returns a Traceback, and creates a ZeroDivisionError object

Using try except code blocks

Write a try exception code block to handle possible exceptions

try:
    print(5 / 0)
except ZeroDivisionError:
    print("You can't divide by zero")

If the code in the try code block runs without problems, the except code block will be skipped;

If the code of the try code block causes an error, Python will look for such an expect code block and run the code in it, that is, the error specified in it is the same as the error raised

Use exceptions to avoid crashes

Often used in programs that require user input

If the program can handle invalid input properly, it can prompt the user to provide valid input again without crashing

division.py

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

while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("\nSecond number: ")
    if second_number == 'q':
        break
    answer = int(first_number) / int(second_number)
    print(answer)

second_ Entering number as 0 will cause the program to crash

else code block

Putting the code that may cause errors in the try except code block can improve the ability of the program to reduce errors

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

while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("\nSecond 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)

The code that depends on the success of the try code block is placed in the else code block

Handling FileNotFoundError exception

cannot find file

alice.py

filename = 'alice.txt'

try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    print("Sorry, the file " + filename + " dose not exist.")

Analyze text

Calculate how many words a text contains

split() method: create a word list according to a string; Split string with space as separator

def count_words(filename):
    """Calculate how many words a file contains"""

    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        print("Sorry, the file " + filename + " dose not exist.")
    else:
        # Calculate how many words the file contains
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + "words.")

filename = 'alice.txt'
count_words(filename)

Fail without saying a word

Explicitly tell Python not to do anything in the expect code block

pass statement: let Python do nothing

except FileNotFoundError:
    pass

There will be no traceback and no output

Decide which errors to report

Use experience to determine where the program contains exception handling blocks and how much relevant information should be provided to the user when an error occurs

Store data

Use the module josn to store data

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

json.dump() stores the data list

import json

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

json.load() reads the list into memory

import json

filename = 'numbers.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)

print(numbers)

Save and read user generated data

import json

#If the user name was previously stored, load it; Otherwise, the user is prompted for a user name and stored
filename = 'name.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What's your name: ")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print("Hello, " + username)
else:
    print("Welcome back, " + str(username) + "!")

restructure

Refactoring: dividing code into a series of functions that do specific work

import json

def get_stored_username():
    """If the user name is stored, get it"""
    filename = 'name.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """Prompt user for user name"""
    username = input("What's your name: ")
    filename = 'name.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
    return username

def greet_user():
    """Greet the user and indicate their name"""
    username = get_stored_username()
    if username:
        print("Welcome back, " + username + "!")
    else:
        username = get_new_username()
        print("We'll remeber you when you come back, " + username + "!")

greet_user()

 

Added by Wozzr on Fri, 26 Nov 2021 00:54:09 +0200