Purpose of this chapter

Learn how to read and write text files, manipulate arrays, manipulate JSON, manipulate XML

1. Read text files

Codes:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

# Read file refers to plain text files, such as TXT or CSV ending files
def read_file(file_name) :
    Try to open the file and read its contents. Use the try Finally for rigor. Because the file may not exist or there may be other exceptions, such as the file is occupied, I/O exception, etc
    try:
        Define a variable f, open {file_name} as read-only, and assign it to f
        f = open(file_name, 'r')
        Step 2: Read all the contents of the file
        print(f.read())
    finally:
        # No matter how many steps come before, they will be executed eventually
        If the file was successfully read, the file must be closed at the end
        if f:
            f.close()


# same function as above, only more elegant writing
def read_file_gracefully(file_name) :
    with open(file_name, 'r') as f:
        print(f.read())


# sometimes we do something to the row and then we print it, we can write it like this
def read_file_inline(file_name) :
    with open(file_name, 'r') as f:
        array = f.readlines()
    for i in range(0.len(array)):
        array[i] = array[i].rstrip('\n')
        print(The f' line is:{array[i]}')


read_file('.. /resources/test.csv')
read_file_gracefully('.. /resources/test.csv')
read_file_inline('.. /resources/test.csv')

Copy the code

The execution result

Write a text file

Code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

Write file, refers to general text files, such as TXT or CSV ending files
def write_file(file_name) :
    try:
        Define a variable f, open the file {file_name}, and assign it to f
        f = open(file_name, 'w')
        f.write('Hello, world! ')
    finally:
        if f:
            f.close()


def write_file_gracefully(file_name) :
    with open(file_name, 'w') as f:
        f.write('Hello, world gracefully! ')


def read_file(file_name) :
    print('-- the content just written is --')
    with open(file_name, 'r') as f:
        print(f.read())


write_file_path = '.. /resources/write_test.txt'
write_file(write_file_path)
read_file(write_file_path)

write_file_gracefully(write_file_path)
read_file(write_file_path)

Copy the code

Execution Result:

TXT file write_test. TXT

3. Operate on arrays

Front rely on

Install Numpy on the terminal

pip3 install numpy

Code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

This library provides multivariable array functionality, much more powerful than ordinary arrays
# Install method
# pip3 install numpy or pip3 install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple/
Numpy is np
import numpy as np

# Expected print
# [1 2 3]
a = np.array([1.2.3])
print(a)

# print integers in [1, 7], each step of size 1
start = 1
end = 7
step = 1
# Expected print
# [1 2 3 4 5 6]
print('---- outputs integers in [1, 7], each step being 1-- ')
print(np.arange(start, end, step, dtype=np.int16))

# print integers in [1, 7], each step of size 2
step = 2
# Expected print
# [1 3 5]
print('---- outputs integers in [1, 7] with steps of 2-- ')
print(np.arange(start, end, step, dtype=np.int16))

# output the integer in [0, 12) in 3 rows and 4 columns
# Expected print
# [[0 1 2 3]
# [4 5 6 7]
# [8 9 10 11]]
print('---- outputs integers in [0, 12] in the format of 3 rows and 4 columns --')
print(np.arange(12).reshape(3.4))

Copy the code

The execution result

4. Manipulate JSON

Code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

# Navigation, to use a different format such as JSON, requires a faster way to do the conversion

Json is a json library
import json

{"name": "Jake", "age": 20} "1. Print the one_person JSON object and format the output.
one_person = {"name": "Jake"."age": 20}
print('-- print one_person-- indent 4')
print(json.dumps(one_person, indent=4))

print('-- print one_person-- shrink by 4 and sort by key value ')
print(json.dumps(one_person, sort_keys=True, indent=4))

2. STR to JSON object ""
result = json.loads('{"name":"Tom", "age":23}')
print('- print the result -)
print(result)

print('-- Print the contents of the test.json file --')
with open(".. /resources/test.json"."r", encoding='utf-8') as f:
    print(f.read())

Copy the code

Execution Result:

5. Manipulate XML

Code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

# Navigation, to use a different format such as JSON, requires a faster way to do the conversion

import os

import xml.sax
import xml.dom.minidom

# xml_str = '<collection shelf="New Arrivals">'\
# '
      
       '\
      
# '
      
       War, Thriller
      '\
# '
      
       DVD
      '\
# ''\
# ''

# with open(".. /resources/movie.xml", "r", encoding='utf-8') as f:
# print(f.read())

DOMTree = xml.dom.minidom.parse(".. /resources/movie.xml")
collection = DOMTree.documentElement

if collection.hasAttribute("shelf") :print("Root element : %s " % collection.getAttribute("shelf"))

movies = collection.getElementsByTagName("movie")

for movie in movies:
    if movie.hasAttribute("title") :print("Title: %s" % movie.getAttribute("title"))

    Get the first occurrence of type in all 
      
        tags
      
    type = movie.getElementsByTagName("type") [0]
    Print the contents of the type node
    print("Type type: %s\n" % type.childNodes[0].data)

Copy the code

Execution Result: