Getting started with Python Xiaobai: files, exception handling and storing data in json format

Materials used

The files used in the code can be downloaded from the following website:
https://www.ituring.com.cn/book/2784
insert image description here

1. Read data from the file

1.1 Read the entire file

insert image description here

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

insert image description here

  • open function

Open a file. The receiving parameter is the file name to be opened . Python will search for the specified file in the directory where the currently executed file is located , so you need to put the pi_digits.txt file in the same directory as the executable file.
The open function returns an object representing the file , and Python assigns the object to file_object through the as keyword .

  • with keyword

Python will automatically close the file when it is no longer needed to access it . It is safer than using the close function (close file function) directly.

  • read function

Read the content of the file and assign it to the contents variable in the form of a string. The read function will return an empty string when it reads to the end of the file, and it will be printed out as a blank line. You can use the rstrip function in the contents to delete the blank line at the end.

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

insert image description here
You can see that the blank lines have been deleted.

1.2 File path

  • Relative path: Search relative to the directory where the currently running program is located. For example, if the currently running program is python_work, there is a folder named files that stores the file.txt file, and the path is: files\file.txt , and python will automatically search for it in python_work.

  • Absolute path : the exact location where the file is stored in the computer, such as: C:Learning\Python from Getting Started to Practice 2nd Edition Source Code Files\Source Code Files\chapter_10 . Because the absolute path is long, the string is usually assigned to a variable file_path first, and then passed into the Open function

Note : Windows systems use backslashes (\) instead of slashes (/) when displaying file paths, but slashes are used to represent paths in code.

1.3 Read line by line

Read the file line by line: use a for loop.

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

Use the for loop to let the variable line represent each line in the file for output.

insert image description here

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

  • readlines function: Reads each line from a file and stores it in a list.
  • readline function: read a line from a file and save it as a string.
file_path = 'files/pi_digits.txt'
with open(file_path) as file_object:
    line = file_object.readline()
    lines = file_object.readlines()

print(line)
print(lines)

The code uses lines to receive a list of the contents of each line in the storage file read by the readlines function.
You can see that there is a newline character after each line.

insert image description here
The read lines can use the for loop to read the content of each line.

1.5 Using the contents of the file

The data can be used after the file has been read into memory.

There are three functions in Python to remove leading and trailing characters and blank characters , which are:

  • strip: Used to remove head and tail characters, blanks (including \n, \r, \t, ' ', namely: newline, carriage return, tab, space)
  • lstrip: used to remove the beginning characters and blanks (including \n, \r, \t, ' ', namely: newline, carriage return, tab, space)
  • rstrip: Used to remove ending characters and blanks (including \n, \r, \t, ' ', namely: newline, carriage return, tab, space)

In order to integrate the content obtained in the file into a string without intermediate blank characters, use the strip function to remove blanks.

blanking function

file_path = 'files\pi_digits.txt'

with open(file_path) as file_objects:
    lines = file_objects.readlines()

pi_strings = ""
for line in lines:
    pi_strings += line.strip()

print(pi_strings)
print(len(pi_strings))
pi_number = float(pi_strings)
print(pi_number)
print(type(pi_number))

The strip function can not only delete the blank characters after each line, but also delete the blank characters at the beginning of each line. In this way, a string of pi_string is obtained.

If you want to calculate the value later, you need to convert the string into a value for use. You can use the float function for type conversion.

insert image description here

1.6 Large files containing a million bits

needed file:

insert image description here

Read a pi file accurate to 1,000,000 decimal places.

file_path = 'files/pi_million_digits.txt'

with open(file_path) as file_objects:
    lines = file_objects.readlines()

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

print(pi_string[:52])
print(len(pi_string))

Print the first 52 digits, and then output the length of the string, which proves that there are indeed 1,000,002 digits.

insert image description here

1.7 Does the value of pi include your birthday?

You can check whether your birthday is in the pi, if it exists, use the index function to find the position of the birthday string in the pi string and output it.

file_path = 'files/pi_million_digits.txt'

with open(file_path) as file_objects:
    lines = file_objects.readlines()

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

birthday = input("Please enter your birthday, in the form mmdd: ")

if birthday in pi_string:
    print(f"Your birthday appears in the first million digits of pi at the index of {
      
      pi_string.index(birthday)}!")
else:
    print("Sorry~")

practice questions

insert image description here
insert image description here

file_path = 'files/learning_python.txt'

with open(file_path) as file_objects:
    contents = file_objects.read()
print(contents)

with open(file_path) as file_objects:
    for line in file_objects:
        print(line.rstrip())

with open(file_path) as file_objects:
    lines = file_objects.readlines()
print(lines)

insert image description here

file_path = 'files/learning_python.txt'

with open(file_path) as f:
    lines = f.readlines()

for line in lines:
    print(line.rstrip().replace('Python','c++'))

insert image description here

2. Write to the file

2.1 Write an empty file

Two arguments are provided when calling open():

  • First argument: the name of the file to open.
  • The second argument ('w'): tells Python to open the file in write mode.

When opening a file, you can specify read mode ('r'), write mode ('w'), append mode ('a'), or read-write mode ('r+') . If the mode argument is omitted, Python will open the file in the default read-only mode.

If the file to be written does not exist, the function open() will automatically create it .

However, be careful when opening files in write mode ('w'), because if the specified file already exists, Python will empty the contents of the file before returning the file object.

Python can only write strings to text files. To store numeric data into a text file, it must first be converted to string format using the function str().

filename = 'programming.txt'

with open(filename,'w') as f:
    f.write('I love programming!')

insert image description here

2.2 Write multiple lines

Add newlines in the writer function.

filename = 'programming.txt'

with open(filename,'w') as f:
    f.write('I love writing!\n')
    f.write('I love programming!\n')

insert image description here

2.3 Appending to a file

If you don't want to overwrite the previous content, but want to add content to the file, you can open the file in append mode (a) .

When opening a file in append mode, Python does not empty the contents of the file before returning the file object, but instead appends the lines written to the file to the end of the file.

If the specified file does not exist, Python will create an empty file for you.

filename = 'programming.txt'

with open(filename,'a') as f:
    f.write('I love painting!\n')
    f.write('I love swimming!\n')

with open(filename) as f:
    lines = f.read()
print(lines)

insert image description here

practice questions

insert image description here

10-3

filename = 'guests.txt'
name = input('enter the name: ')
with open(filename,'w') as f:
    f.write(name.title())

10-4

filename = 'guest_book.txt'
with open (filename,'a') as f:
    while True:
        name = input("Enter the name: ")
        if name == 'q':
            break
        print(f"Hi, {
      
      name.title()} !")
        f.write(f"{
      
      name.title()}\n")

insert image description here
insert image description here
10-5

filename = 'reason.txt'
with open(filename,'a') as f:
    while True:
        reason = input('Enter the reason why you like programming')
        if reason=='quit':
            break
        f.write(f"{
      
      reason}\n")

3. Abnormal

Exception: A special object that manages errors that occur during program execution.
Whenever an error occurs that overwhelms Python, it creates an exception object. If you write code to handle the exception, the program will continue to run; if the exception is not handled, the program will stop and display a traceback, which contains a report about the exception.

Exceptions are handled using try-except code blocks.
The try-except block tells Python what to do when an exception occurs. When using a try-except code block, the program will continue to run even if an exception occurs: displaying a friendly error message you write instead of a traceback that confuses the user.

3.1 ZeroDivisionError exception

ZeroDivisionError exception: the dividend cannot be 0 exception.

insert image description here

3.2 Using the try-except module

When you think that an error may occur, you can write a try-except code block to handle the exception that may be thrown.

  • write down try to let Python try to run some code,
  • except writes what to do if the code throws the specified exception.
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero! ")

Put the error-causing line print(5/0) in a try block. If the code in the try code block runs without problems, Python will skip the except code block; if the code in the try code block causes an error, Python will find a matching except code block and run the code in it.

In this example, the code in the try block raised a ZeroDivisionError exception, so Python looks for the except block that tells what to do, and runs the code in it. This way, the user sees a friendly error message instead of a traceback.

3.3 try - except - else block

Use try-except for exception handling, and code that depends on the successful execution of the try code block should be placed in the else code block.

while True:
    n1 = input("First number: ")
    if n1 == 'q':
        break
    n2 = input('Second number: ')
    if n2 == 'q':
        break
    try:
        result = int(n1)/int(n2)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(result)

insert image description here

3.4 Handling FileNotFoundError exceptions

FileNotFoundError exception: file not found
insert image description here

filename = 'alice.txt'

try:
    with open(filename) as f:
        contents = f.read()
        
except FileNotFoundError:
    print(f"{
      
      filename} doesn't exit!")

insert image description here

3.5 Analyzing characters of text

Count the number of all English words in the alice.txt file.
insert image description here

  • split() function: Create a word list for the English words in a string
  • encoding = 'utf-8': used when the system default encoding is inconsistent with the encoding used to read the file.
filename = 'alice.txt'

try:
    with open(filename,encoding = 'utf-8') as f:
        contents = f.read()

except FileNotFoundError:
    print(f"{
      
      filename} doesn't exit!")

else:
    words = contents.split()
    num_word = len(words)
    print(f"The file {
      
      filename} has about {
      
      num_word} words.")

insert image description here

3.6 Analyzing multiple files

filenames = [‘alice.txt’,‘siddhartha.txt’,‘mobd_dick.txt’]

Where siddhartha.txt file does not exist. Use a for loop to read and analyze the files in the file list at one time.

def count_words(filename):
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()

    except FileNotFoundError:
        print(f"{
      
      filename} doesn't exit!")

    else:
        words = contents.split()
        num_word = len(words)
        print(f"The file {
      
      filename} has about {
      
      num_word} words.")

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

insert image description here

3.7 Keep silent when encountering exceptions

If you want the program to say nothing when an exception occurs, and continue to execute as if nothing happened, then use the pass statement under the except module .

def count_words(filename):
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()

    except FileNotFoundError:
        pass

    else:
        words = contents.split()
        num_word = len(words)
        print(f"The file {
      
      filename} has about {
      
      num_word} words.")

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

insert image description here

practice questions

insert image description here
insert image description here

10-6

try:
    n1 = int(input("the first number is :"))
    n2 = int(input("The second number is :"))
except ValueError:
    print("Please enter number not text!")
else:
    print(n1+n2)

10-7

while True:
    try:
        n1 = int(input("the first number is :"))
        n2 = int(input("The second number is :"))
    except ValueError:
        print("Please enter number not text!")
    else:
        print(n1+n2)

10-8

4. Store data

The JSON format: a storage data structure originally developed for JavaScript but has since become a common format adopted by many languages ​​including Python.

The module json enables you to dump simple Python data structures to a file and load the data from that file when the program is run again.

You can also use json to share data between Python programs.

More importantly, the JSON data format is not specific to Python, and data stored in JSON format can be shared with other programming languages.

4.1 Using json.dump( ) and json.load( )

  • Function json.dump(): Store data in a file. Takes two arguments, the data to store, and a file object that can be used to store the data.

  • json.load() : Read data into memory.

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

First import the json module, then use json.dump to store the list of numbers into the number.json file.

insert image description here

Use json.load(f) to store the data structure in the numbers.json file into memory, and then print it out.

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

insert image description here

4.2 Saving and reading user-generated data

Guess you like

Origin blog.csdn.net/weixin_45662399/article/details/132207200