Python learning record

Posted by MysticFallout on Fri, 18 Feb 2022 17:27:53 +0100

1, Function

1. Function creation and call

  • What is a function

    A function is a piece of code that performs a specific task and completes a specific function

  • Why do I need a function

    Reuse code

    Hide implementation details

    Improve maintainability

    Improve readability and facilitate debugging

  • Function creation

    def		Function name([input parameter ]) : 
    	Function body
        [return xxx]
    

2. Parameter transfer of function

  • Parameter transfer of function transfer

    • Position argument

      The argument is passed according to the position corresponding to the formal parameter

    • Keyword argument

      The argument is passed according to the formal parameter name

def calc(a, b):  # a. B becomes a formal parameter, abbreviated as a formal parameter. The position of the formal parameter is defined in the function
    c = a + b
    return c


result = calc(10, 20)  # 10,20 become the value of the actual parameter, which is referred to as the actual parameter for short. The position of the actual parameter is where the function is called
print(result)

res = calc(b=10, a=20)  # =The name of the variable on the left becomes a keyword parameter
print(res)
  • Parameter transfer memory analysis diagram of function call

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qziqigy0-1645159925227) (C: \ users \ saudade \ appdata \ roaming \ typora \ typora user images \ image-20220211202952781. PNG)]

def fun(arg1, arg2):
    print('arg1=', arg1)  # arg1= 11
    print('arg2=', arg2)  # arg2= [22, 33, 44]
    arg1 = 100
    arg2.append(10)
    print('arg1=', arg1)  # arg1= 100
    print('arg2=', arg2)  # arg2= [22, 33, 44, 10]


n1 = 11
n2 = [22, 33, 44]
print(n1)  # 11
print(n2)  # [22, 33, 44]
print("__________________")
fun(n1, n2)	# Talking about the location transfer parameters, arg1, arg2, the formal parameters at the definition of the potential function, n1 and n2 are the actual parameters for the function call. In summary, the name of the actual parameter and the name of the formal parameter can be different
print(n1)  # 11
print(n2)  # [22, 33, 44,10]
"""In the process of function call, parameters are passed
 If it is an immutable object, the modification in the function body will not affect the value of the argument    arg1 The modification of is 100, which will not affect n1 Value of
 If it is a variable object, the modification in the function body will affect the value of the argument arg2 Modification of append(10),Will not affect n2 Value of"""

3. Return value of function

Return value of function
(1) If the function does not have a return value [after the function is executed, there is no need to provide data to the caller], you can omit writing
(2) The return value of the function. If it is 1, it returns the type directly
(3) The return value of the function. If it is multiple, the returned result is tuple

Whether a function needs to return a value when it is defined depends on the situation

def fun(num):
    odd = []  # Deposit base
    even = []  # Save even number
    for i in num:
        if i % 2:
            odd.append(i)
        else:
            even.append(i)
    return odd, even


print(fun([10, 29, 34, 23, 44, 53, 55]))  # ([29, 23, 53, 55], [10, 34, 44])
"""Return value of function
(1)If the function does not have a return value [after the function is executed, there is no need to provide data to the caller], you can omit writing
(2)The return value of the function. If it is 1, it returns the type directly
(3)The return value of the function. If it is multiple, the returned result is tuple"""


def fun1():
    print('hello')
    return


fun1()


def fun2():
    return 'hello'


res = fun2()
print(res)


def fun3():
    return 'hello'
    return 'world'


print(fun3())
"""Whether a function needs to return a value when it is defined depends on the situation"""

4. Parameter definition of function

  • Function definition default parameter value

When defining a function, set the default value for the formal parameter. Only when it is inconsistent with the default value, you need to pass the argument

def fun(a, b=10):  # The default value is b
    print(a, b)


# Function call
fun(100)  # 100 10
fun(20, 30)  # 20 30
  • Variable number of position parameters

When defining a function, you may not be able to determine the number of positional arguments passed in advance. Use variable positional parameters

Use * to define a variable number of position parameters

The result is a tuple

def fun(*args):
    print(args)


fun(10)
fun(10, 30)
fun(30, 400, 50)

# (10,)
# (10, 30)
# (30, 400, 50)
  • Variable number of keyword parameters

    When defining a function, variable keyword parameters are used when the number of keyword arguments passed cannot be determined in advance

    Use * * to define a variable number of keyword parameters

    The result is a dictionary

def fun1(**args):
    print(args)


fun1(a=10)
fun1(a=10, b=20, c=40)

# {'a': 10}
# {'a': 10, 'b': 20, 'c': 40}
'''def fun2(*args,*s):
    pass
    In the above code, the program will report an error. There can only be one variable number of location parameters'''

'''def fun3(**args,**args):
    pass
    In the above code, the program will report an error. There can only be one variable number of keyword parameters'''

def fun4(*args, **args2):
    pass


'''def fun5(**args1,*args2):
    pass'''
# In the process of defining a function, you can have both a variable number of keyword parameters and a variable number of position parameters. It is required that the variable number of position parameters be placed before the variable number of keyword parameters
  • Parameter summary of function

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-0suqn4or-1645159925231) (C: \ users \ saudade \ appdata \ roaming \ typora \ typora user images \ image-20220215180631284. PNG)]

def fun(a, b, c):  # a. B and C are at the definition of the function, so they are formal parameters
    print('a=', a)
    print('b=', b)
    print('c=', c)


# Function call
fun(10, 20, 30)  # When a parameter is passed by correspondence, it becomes a parameter
lst = [11, 22, 33]
fun(*lst)  # When a function is called, each element in the list is converted into a positional argument

fun(a=100, c=300, b=200)  # Function, so it is a keyword argument
dict = {'a': 111, 'b': 222, 'c': 333}
fun(**dict)  # When the function is called, the key value pairs in the dictionary are converted into keyword arguments
def fun4(a, b, *, c, d):  # Parameters after * can only be passed by keyword during function call
    print('a=', a)
    print('b=', b)
    print('c=', c)
    print('d=', d)


"""Demand, c and d Can only be passed by keyword"""
# Call fun4 function
# fun4(10, 20, 30, 40)  # Position argument passing
fun4(a=10, b=20, c=30, d=40)  # Keyword argument passing
fun4(10, 20, c=30, d=40)  # The first two parameters are passed by position arguments; The last two parameters are passed by keyword arguments

5. Scope of parameter

  • Scope of variable

    • The area where the program code can access the variable
    • According to the effective range of variables, they can be divided into
      • local variable
        • Variables defined and used in the function are only valid inside the function. If local variables are declared with global, this variable will become a global variable
      • global variable
        • Variables defined outside the function can act inside and outside the function
def fun(a, b):
    c = a + b  # c. It becomes a local variable, because the variables defined by C in the function body, a and b are the formal parameters of the function, and the scope of action is also within the function, which is equivalent to a local variable
    print(c)


# print(c)
# print(a)
# An error is reported because a and c are out of scope (out of scope)

name = 'saudade'
print(name)


def fun2():
    print(name)


fun2()


def fun3():
    global age  # The variables, local variables and mutual invariants defined inside the function are declared by global, and this variable actually becomes a global variable 
    age = 10
    print(age)


fun3()
print(age)

6. Recursive function

  • What is a recursive function

    • If the function itself is called in the function body of a function, the function becomes a recursive function
  • Components of recursion

    • Recursive call and recursive termination condition
  • Recursive calling procedure

    • Every time the function is called recursively, a stack frame will be allocated in the stack memory
    • Each time the function is executed, the corresponding space is released
  • Advantages and disadvantages of recursion

    • Disadvantages: it takes up too much memory and is inefficient
    • Advantages: simple thinking and code
  • Use recursive factorial

def fac(n):
    if n == 1:
        return 1
    else:
        return n * fac(n - 1)


print(fac(6))	# 720
  • Fibonacci sequence

def fib(n):
    if n == 1:
        return 1
    elif n == 2:
        return 1
    else:
        res = fib(n - 1) + fib(n - 2)
        return res


# The number on the 6th place of Fibonacci series
print(fib(6))

# Output the first six digits of this sequence
for i in range(1, 7):
    print(fib(i))

2, The origin of BUG

1. The origin and classification of bugs

  • The origin of Bug

    • An evolutionary version of the world's first universal computer -- Mark II
  • DeBug

  • Common types of bugs

    • Syntax error caused by carelessness SyntaxError

      • The colon at the end is omitted, such as if statement, loop statement, else clause, etc
      • Indent error, what should be indented is not indented, and what should not be indented is blindly indented
      • Write English symbols into Chinese symbols, such as quotation marks, colons and brackets
      • When splicing strings, put strings and numbers together
      • There is no variable defined, such as the variable of loop condition of while
      • **Mixture of "= =" comparison operator and "=" * * assignment operator
    • Mistakes caused by unskilled knowledge points

      • Index out of bounds IndexError
      lst = [11, 22, 33, 44]
      print(lst[4])
      # The index of the list starts at 0
      # IndexError: list index out of range
      
      • Not proficient in the use of append() method
      lst = []
      lst.append('a', 'b', 'c')
      # TypeError: append() takes exactly one argument (3 given)
      # The append method adds one element at a time
      print(lst)
      
    • Problems caused by unclear ideas (solutions)

      • Use the print() function
      • Use "#" to temporarily comment part of the code
      • Example: ask to enter the name on the screen, which movie did * * * play
      lst = [{'rating': [9.7, 2062397], 'id': '1292052', 'type': ['Crime', 'plot'], 'title': 'The Shawshank Redemption',
              'actors': ['Tim·Robbins', 'morgan ·Freeman']},
             {'rating': [9.6, 1528760], 'id': '1291546', 'type': ['plot', 'love', 'Same sex'], 'title': 'Farewell to my concubine',
              'actors': ['Zhang Guorong', 'Zhang Fengyi', 'Gong Li', 'Ge you']},
             {'rating': [9.5, 1559181], 'id': '1292720', 'type': ['plot', 'love'], 'title': 'Forrest Gump',
              'actors': ['Tom·Hanks', 'Robin·White ']}
             ]
      
      name = input('Please enter the actor you want to query:')
      for item in lst:  # Traversal list -- > {} item is one dictionary after another
          act_lst = item['actors']
          print(act_lst)
          for actor in act_lst:
              if name in actor:
                  print(name, 'Starred', item['title'])
      
    • Passive drop: the logic of the program code is not wrong, but the program crashes due to the user's wrong operation or some "exceptions"

      • Example: enter two integers and divide
      a = int(input('Please enter the first integer:'))
      b = int(input('Please enter the second integer:'))
      result = a / b
      print('The result is:', result)
      
      # Please enter the first integer: 23
      # Please enter the second integer: 0
      # Traceback (most recent call last):
      #   File "C:/Space_Python/practice/chap11/demo4.py", line 9, in <module>
      #     result = a / b
      # ZeroDivisionError: division by zero
      
      • Solution: Python provides an exception handling mechanism, which can catch exceptions in time when they occur, and "digest" them internally after people, so that the program can continue
      try:
          a = int(input('Please enter the first integer:'))
          b = int(input('Please enter the second integer:'))
          result = a / b
          print('The result is:', result)
      except ZeroDivisionError:
          print('Error, divisor cannot be 0')
      except ValueError:
          print('No number entered')
      print('Program end')
      

2. Exception handling mechanism

  • Use to catch exception try -- exception

  • Multiple except structures

    • Exceptions are caught in the order of subclasses before superclasses. In order to avoid missing possible exceptions, BaseException can be added at last
  • try... except... else structure

    • If no exception is thrown in the try block, else block is executed; if an exception is thrown in the try block, except block is executed
    try:
        a = int(input('Please enter the first integer:'))
        b = int(input('Please enter the second integer:'))
        result = a / b
    except BaseException as e:
        print('Error ', e)
    else:
        print('The result is', result)
    
  • try... except... else... finally structure

    • finally, the block will be executed no matter whether there is an exception or not, which can be commonly used to release the resources applied in the try block
    try:
        a = int(input('Please enter the first integer:'))
        b = int(input('Please enter the second integer:'))
        result = a / b
    except BaseException as e:
        print('Error ', e)
    else:
        print('The result is', result)
    finally:
        print('Thank you for your use')
    

4. Python's exception handling mechanism

  • Common exception types

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8ygtwcfa-1645159925232) (C: \ users \ saudade \ appdata \ roaming \ typora \ typora user images \ image-20220216144228490. PNG)]

# (1) Abnormal mathematical operation
# print(10 / 0)
# ZeroDivisionError: division by zero

# (2) Index exception
lst = [11, 33, 44, 55]
# print(lst[4])
# IndexError: list index out of range

# (3)
dict = {'name': 'Zhang San', 'age': 20}
# print(dict['abc'])
# KeyError: 'abc'

# (4)
# print(name)
# NameError: name 'name' is not defined

# (5)
# int age =20
# SyntaxError: invalid syntax

# (6)
a=int('hello')
# ValueError: invalid literal for int() with base 10: 'hello'
  • traceback module

    • Use the teacback module to print exception information
    import traceback
    
    try:
        print("---------------")
        print(10 / 0)
    except:
        traceback.print_exc()
    

3, Object oriented programming idea

1. Two ideas of programming

Process orientedobject-oriented
differenceThings are relatively simple and can be solved by linear thinkingThings are complicated and cannot be solved by simple linear thinking
common groundBoth object-oriented and process oriented are a way of thinking to solve practical problems
summaryThe two complement each other and are not opposite.
To solve complex problems, the object-oriented method is convenient for us to grasp the complex relationship before things from a macro perspective and analyze the whole system
When it comes to micro operations, the process oriented approach is still used

2. Creation of classes and objects

  • class

    • Class is the general name of a group composed of many similar things. It can help us quickly understand and judge the nature of things
  • data type

    • Different data types belong to different classes
    • Use built-in functions to view data types (type())
  • object

    • 100, 99520 are similar and different examples contained under the int class, which are professionally called instances or objects
  • Class creation

    • Syntax for creating classes

      class Student:
          pass
      
    • Composition of classes

      • Class properties
      • Example method
      • Static method
      • Class method
      class Student:  # Student is the name of the class (class name), which is composed of one or more words. The first letter of each word is uppercase and the rest is lowercase
          native_place = 'ynz '  # Class properties, variables written directly in the class
      
          def __init__(self, name, age):
              self.name = name  # self.name becomes an instance attribute, performs an assignment operation, and assigns the value of the name of the local variable to the instance attribute
              self.age = age
      
          # Example method
          def eat(self):
              print('The students are eating...')
      
          # Static method
          @staticmethod
          def method():
              print("I used it staticmethod Modification, so I'm a static method")
      
          # Class method
          @classmethod
          def cm(cls):
              print("I used it classmethod Modification, so I'm a class method")
      
      
      # What is defined outside the class becomes a function, and what is defined inside the class is called a method
      def drink():
          print('Drinking water')
      
  • Object creation

    • Object creation is also called class instantiation

    • grammar

      Instance name=Class name ()
      
    • significance

      With an instance, you can call the content in the class

    # Create the object of Student class, instance object
    stu1 = Student('Zhang San', 20)
    stu1.eat()  # Object name Method name ()
    print(stu1.name)
    print(stu1.age)
    
    print("----------------------")
    Student.eat(stu1)   # Function and stu1 Eat () is the same, which calls the eat method in Student
                        # Class name Method name (object of class) -- > the actual thought is self at the method definition
    

3. Class object and class attribute, class method and static method

  • Class properties

    • Variables outside the methods in the class become class properties and are accessed by all objects of the class
  • Class method

    • Methods decorated with @ classmethod and directly accessed by class name
  • Static method

    • Methods decorated with @ staticmethod and directly accessed by class name
  • Mode of use

# How class properties are used
print(Student.native_place)
stu1 = Student('Zhang San', 20)
stu2 = Student('Li Si', 30)
print(stu1.native_place)
print(stu2.native_place)
Student.native_place = 'Beijing'
print(stu1.native_place)
print(stu2.native_place)

print("-----------How class methods are used------------")
Student.cm()

print("-----------How static methods are used------------")
Student.method()
  • Dynamic binding properties and methods

    • python is a dynamic language. After creating objects, you can dynamically bind properties and methods
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print(self.name + 'be at  table')


stu1 = Student('Zhang San', 20)
stu2 = Student('Li Si', 30)

print("----------by stu2 Add gender attribute dynamically-------------------")
stu2.gender = 'female'
print(stu1.name, stu1.age)
print(stu2.name, stu2.age, stu2.gender)

print("----------------")
stu1.eat()
stu2.eat()

print("---------Dynamic binding method--------")


def show():
    print("Those defined outside the class are called functions")


stu1.show = show
stu1.show()

4, Object oriented

1. Encapsulation: improve program security

  • Three characteristics of object-oriented

    • Encapsulation: improve program security
      • Wrap data (properties) and behavior (Methods) into class objects. The attribute memory operation is performed inside the method, and the method is called outside the class object. In this way, we care about the specific implementation details inside the method, thus isolating the complexity
      • In python, there is no special modifier for the private of the attribute. If the attribute does not want to be accessed outside the class object, the first two "" are used
    class Student:
        def __init__(self, name, age):
            self.name = name
            self.__age = age  # Age doesn't want to be used outside the class, so add two_
    
        def show(self):
            print(self.name, self.__age)
    
    
    stu = Student("Zhang San", 20)
    stu.show()
    
    # Use name and age outside the class
    print(stu.name)
    # print(stu.__age)
    # AttributeError: 'Student' object has no attribute '__age'
    
    # print(dir(stu))
    print(stu._Student__age)  # Outside the class, you can_ Student__age for access
    

2. Inheritance: improve code reusability

  • Syntax format

class Subclass class name (parent class 1, parent class 2)...)	:
	pass
  • If a class does not inherit any classes, it inherits obiect by default
  • Python supports multiple inheritance
  • The definition of a subclass is that the constructor of the parent class must be called in its function.
class Person(object):  # Person inherits the obiect class
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        print(self.name, self.age)


class Student(Person):
    def __init__(self, name, age, stu_no):
        super().__init__(name, age)
        self.stu_no = stu_no


class Teacher(Person):
    def __init__(self, name, age, teachoyear):
        super().__init__(name, age)
        self.teachoyear = teachoyear


stu = Student('Zhang San', 20, "1001")
teacher = Teacher("Li Si", 34, 10)

stu.info()
teacher.info()

3. Method rewrite

  • If a subclass is not satisfied with a property or method inherited from the parent class, it can rewrite it (method body) in the subclass
  • Subclass overridden methods can be overridden through super() Xxx() calls the overridden method in the parent class
class Person(object):  # Person inherits the obiect class
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        print(self.name, self.age)


class Student(Person):
    def __init__(self, name, age, stu_no):
        super().__init__(name, age)
        self.stu_no = stu_no

    def info(self):
        super().info()
        print(self.stu_no)


class Teacher(Person):
    def __init__(self, name, age, teachoyear):
        super().__init__(name, age)
        self.teachoyear = teachoyear

    def info(self):
        super(Teacher, self).info()
        print("Teaching age",self.teachoyear)


stu = Student('Zhang San', 20, "1001")
teacher = Teacher("Li Si", 34, 10)

stu.info()
print("--------------------")
teacher.info()

4. obiect class

  • The object class is the parent class of all classes, so all classes have the properties and methods of the obiect class
  • The built-in function dir() can view all properties of the specified object
  • Obiect has one_ str_ () method, which is used to return a description of the "object", corresponding to the built-in function str(), which is often used in the print() method to help us view the information of the object, so we often_ str_ () Rewrite
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):  # Rewrite str method
        return 'My name is{0},this year{1}year'.format(self.name, self.age)


stu = Student('Zhang San', 20)
print(dir(stu))

print(stu)
print(type(stu))

5. Polymorphism: improve program scalability and maintainability

  • To put it simply, polymorphism means "having multiple forms". It means that even if you don't know what type of object a variable refers to, you can still call methods through this variable. In the running process, you can dynamically decide which object method to call according to the type of object referenced by the variable
class Animal(object):
    def eat(self):
        print("Animals can eat")


class Dog(Animal):
    def eat(self):
        print("Dogs eat bones")


class Cat(Animal):
    def eat(self):
        print("Cats eat fish")


class Person():
    def eat(self):
        print("People eat cereals")


# Define a function
def fun(obj):
    obj.eat()


fun(Cat())
fun(Dog())
fun(Animal())
print("--------------------")

fun(Person())

6. Special methods and properties

  • Special methods and properties

namedescribe
Special properties“"_ _ dict _ _"Get the dictionary of all properties and methods bound by the class object or instance object
Special method"_ _ len_ _"By rewriting "_ len _ _ "Method, so that the parameters of the built-in function len() can be custom types
"_ _ add_ _"By rewriting "_ add _ _ "Method to make the custom object have" + "function
"_ _ new_ _"Used to create objects
"_ _ init_ _"Initialize the created object
  • Shallow copy and deep copy of class

    • Assignment of variables
      • Just form two variables, in fact, only want the same object
    • Shallow copy
      • python copy generally loses the shallow copy. When copying, the sub object content contained in the object will not be copied. Therefore, the original object and the copied object will reference the same sub object
    • Deep copy
      • Use the deepcopy function of the copy module to recursively copy the sub objects contained in the object, and all sub objects of the original object and the copied object are also different
class CPU:
    pass


class Disk:
    pass


class Computer(CPU, Disk):
    def __init__(self, cpu, disk):
        self.cpu = cpu
        self.disk = disk


# (1) Assignment of variables
cpu1 = CPU()
cpu2 = cpu1
print(cpu1)  # An object is put into two variables
print(cpu2)

# (2) Shallow copy of class
print("--------------")
disk = Disk()  # Create an object of Disk class
computer = Computer(cpu1, disk)  # Create an object of Computer class

# Shallow copy
import copy

computer2 = copy.copy(computer)
print(computer, computer.cpu, computer.disk)
print(computer2, computer2.cpu, computer2.disk)


# Deep copy
print("-------------")
computer3=copy.deepcopy(computer)
print(computer, computer.cpu, computer.disk)
print(computer3, computer3.cpu, computer3.disk)

5, Module

1. What is a module

  • modular:

    • English of Modules - Modules
    • Relationship between function and module
      • A module can contain N more functions
    • In python, an extension is py file is a module
    • Benefits of using modules
      • Facilitate the import and use of other programs and scripts
      • Avoid conflicts between function and variable names
      • Improve code maintainability
      • Improve code reusability

2. Custom module

3. Execute in the form of main program

  • The definition of each module includes a variable _that records the module name_ name _ , The program can check the variables to determine which module they are executed in. If a module is not imported into other programs for execution, it may be executed in the top-level module of the interpreter. Top level module_ name _ The value of the variable is __ main _ _
def add(a, b):
    return a + b


if __name__ == '__main__':
    print(add(10, 20))          # Only when you click Run calc2 yes, the operation will be executed

4. Packages in python

  • Package is a hierarchical directory structure, which organizes a group of modules with similar functions in a directory
  • effect:
    • Code specification
    • Avoid module name conflicts
  • Difference between package and directory
    • Include_ init _ _. The directory of the PY file is called the package
    • Directories usually don't contain __ init _ _.py file
  • Import of packages
    • import package name Module name
  • Attention
# Considerations when importing modules with packages
import package1
import calc
# Using the import method, you can only follow the package name or module name

from package1 import moduleA
from package1.moduleA import a
# Use from import.. You can import packages, modules, functions and variables

5. Built in modules commonly used in python

Module namedescribe
sysStandard libraries related to the Python interpreter and its environment operations
timeProvides a standard library of various functions related to time
osProvides a standard library for accessing operating system service functions
calendarProvides a standard library of various functions related to date
urllibStandard library for reading data from the Internet (server)
jsonUsed to serialize and deserialize objects using JSON
reUsed to perform regular expression matching and substitution in strings
mathProvides a standard library of standard arithmetic operator functions
decimalDecimal operation for precise control of operation accuracy, significant digits and rounding operation
loggingIt provides flexible recording time, operation and warning

6. Installation and use of third-party modules

  • Installation of third-party modules
    • pip install module name
  • Use of third-party modules
    • import module name

6, File operation

1. Introduction to coding format

  • Common character encoding formats
    • python's interpreter uses Unicode (memory)
    • . py files are stored on disk using UTF-8 (external storage)

2. Reading and writing principle of documents

  • File reading and writing is commonly known as "IO operation"
  • File reading and writing operation process
    • python operation file - > open or create file - > read / write file - > Close resource

3. File read / write operation

  • The built-in function open() creates a file object
  • rule of grammar
    • file = open ( filename [,mode,encoding])

4. Common methods for file objects

  • Type of file
    • According to the organization form of data in the file, the file is divided into the following two categories
      • Text file: it stores ordinary "character" text, which defaults to unicode character set and can be opened using Notepad program
      • Binary file: the data content is stored in "bytes", which cannot be opened with Notepad. It must be opened with special software, such as mp3 audio file, jpg picture, doc document, etc
Open modedescribe
rWhen you open a file in read-only mode, the pointer to the file will be placed at the beginning of the file
wOpen the file in write only mode. If the file does not exist, create it. If the file exists, overwrite the original content. The file pointer is at the beginning of the file
aOpen the file in append mode. If the file does not exist, create it. The file pointer is at the beginning of the file. If the file exists, append content at the end of the file, and the file manufacturing is at the end of the source file
bOpen the file in binary mode. It cannot be used alone. It needs to be used together with other modes, rb or wb
+Open the file in read-write mode. It cannot be used alone. It needs to be used together with other modes. a+
  • Common methods of file objects
Method nameexplain
read([size])Read the content of size bytes or characters from the file and return it. If [size] is omitted, it will be read to the end of the file and all the contents of the file will be read at one time
readline()Read a line from a text file
readlines()Take each line in the text as an independent string object, and put these objects into the list to return
write(str)Write string str contents to file
writelines(s_list)List string s_list writes to the text file without adding line breaks
seek(offset[,whence])Move the text pointer to a new position. offset indicates the position relative to where:
offset: positive to the end and negative to the start
Different values of where indicate different meanings:
0: calculated from the file header (default)
1: Calculate from current position
2: Calculate from the end of the file
tell()Returns the current position of the file pointer
flush()Writes the contents of the buffer to the file without closing the file
close()Write the contents of the buffer into the file, close the file and release the resources related to the file object

5. with statement (context manager)

  • The with statement can automatically manage context resources. No matter what reason jumps out of the with block, it can ensure that the file is closed correctly, so as to release resources
with open("logo.png", "rb") as src_file:
    with open("copy2log.png", "wb") as target_file:
        target_file.write(src_file.read())

6. Directory operation

  • OS module is Python's built-in module related to operating system functions and file system. The execution results of the statements of this module are usually related to the operating system. When running on the non-stop operating system, the results may be different
  • OS module and OS The path module is used to operate on directories or files
  • OS module operation directory related functions
functionexplain
getcwd()Returns the current working directory
listdir(path)Returns the file and directory information under the specified path
mkdir(path[,mode])Create directory
mkdirs(path1/path2...[,mode])Create multi-level directory
rmdir(path)Delete directory
removedirs(path1/path2...)Delete multilevel directory
chdir(path)Set path to the current working directory
  • os. The path module operates the functions related to the directory
functionexplain
adspath(path)Used to get the absolute path of a file or directory
exists(path)Used to judge whether a file or directory exists. If it exists, it returns true; otherwise, it returns False
join(path,name)Concatenate a directory with a directory or file name
splitext()Separate file name and extension
basename(path)Extract file names from a directory
dirname(path)Extract the file path from a path, excluding the file name
isdir(path)Used to determine whether it is a path
  • Exercise 1: get all py files in the specified directory
# Lists all py files in the specified directory
import os

path = os.getcwd()
lst = os.listdir(path)
print(path)
print(lst)
for filename in lst:
    if filename.endswith(".py"):
        print(filename)
  • Exercise 2: traverse all files in the directory
# Traverse all files in the directory
import os

path = os.getcwd()
lst_files = os.walk(path)
for dirpath, dirname, filename in lst_files:
    """print(dirpath)
    print(filename)
    print(dirname)
    print("------------")"""
    for dir in dirname:
        print(os.path.join(dirpath, dir))
    for file in filename:
        print(os.path.join(dirpath, file))
    print("----------")

Topics: Python