The last part of Python learning

catalogue

Scope of variable

1. Scope of variables

(1) The area where the program code can access the variable

(2) According to the effective range of variables, they can be divided into

Recursive function

1. What is a recursive function

2. Components of recursion

3. Recursive call procedure

4. Advantages and disadvantages of recursion

5. Fiboracci sequence:

  exception handling

1. Python's exception handling mechanism

2. Multiple except structures

  3. try...except...else...finally structure

(1) 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

(2) Illustration:

4. Common exception types in python

5 exception handling module traceback

6. Debugging of pycharm development environment

(1) Breakpoint

(2) Enter debug view

(3) After entering the debugging platform, click the down arrow to enter the next debugging step

Two ideas of programming: process oriented and object-oriented

Classes and objects

1. Class

2. Data type

3. Object

Class creation

1. Syntax for creating classes

2. Composition of classes

3. Illustration:

Object creation

1. Object creation is also called class instantiation

2. Syntax:

3. Example:

4. Illustration:

Class attribute, class method, static method

Dynamic binding properties and methods

1. Python is a dynamic language that can dynamically bind properties and methods after creating objects

2. Illustration

  3. Examples of corresponding diagrams:

  Three characteristics of object oriented

1. Encapsulation: improve program security

2. Inheritance: improve code reusability

3. Polymorphism: improve program scalability and maintainability

4. Packaging example:

5. Inherit

(1) Syntax format

(2) If a class does not inherit any classes, it inherits object by default

(3) Python supports multiple inheritance

(4) when defining a subclass, the constructor of the parent class must be called in its constructor.

(5) Multiple inheritance examples:

6. Method rewrite

  7. object class

8. Polymorphism

  9. Special properties and methods

10. Shallow and deep copies of classes

(1) Assignment operation of variable

(2) Shallow copy

(3) Deep copy

(4) Example of variable assignment:

  modular

1. Module

2. Relationship between function and module

3. In Python, a file with the. py extension is a module

4. Benefits of using modules

5. Custom module

(1) Create module

(2) Import module

(3) Module import (self created module)

(4) Run in the form of main program

6. Packages in Python

(1) Package is a hierarchical directory structure, which organizes a group of modules with similar functions in a directory

(2) Function:

(3) Difference between package and directory

(4) Import of packages

  7. Content module for warehouse in python

Installation and use of third modules

  Coding format

File reading and writing

  Common file opening modes

1. Type of file

with statement

1. with statement (context manager)

Operation directory

Scope of variable

1. Scope of variable

(1) The area where the program code can access the variable

(2) 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

example:

def fun(a,b):
    c=a=b  #c. It is called a local variable, because the variables A and b defined in the real function of C are the formal parameters of the function, and the general range is also within the function, which is equivalent to a local variable
    print(c)

#print(c) will report an error because a and C are beyond the scope of their functions
#print(a)


name='Miss Yang'
def fun2():
    print(name)

#Call function

fun2()


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

fun3()
print(age)

Output results:

Recursive function

1. What is a recursive function

If the function itself is called in the function body of a function, the function is called a recursive function

2. Components of recursion

Recursive call and recursive termination condition

3. Recursive call 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

4. Advantages and disadvantages of recursion

Disadvantages: it takes up too much memory and is inefficient

Advantages: simple idea and code

example:

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

print(fac(6))

Output results:

5. Fiboracci sequence:

Item 1: 1

Item 2: 1

Item 3: 2

Item 4: 3

Item 5: 5

. . . . . .

That is, it is equal to the sum of the first two results

example:

#Implementation of fiboracci sequence
def fib(n):
    if n==1:
        return 1
    elif n==2:
        return 1
    else:
        return fib(n-1)+fib(n-2)

#A number in the 6-digit fiboracci sequence
print(fib(6))
print('---------------------')

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

Output results:

  exception handling

1. Python's exception handling mechanism

Solution to the problem of passive pit falling

Python provides an exception handling mechanism, which can catch the exception immediately when it occurs, and then "digest" it internally to let the program continue to run

2. Multiple except structures

Exceptions are captured in the order of subclasses before parent classes. To avoid missing possible exceptions, BaseException can be added at the end

  example:

ry:
    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('Sorry, divisor 0 is not allowed')
except ValueError:
    print('Only numeric strings can be entered')
print('Program end

Output results:

 

  3. try...except...else...finally structure

(1) 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:

n1=int(input('Please enter an integer: ∵))

n2=int(input('Please enter another integer: ')

result=n1/n2

except  BaseException  as   e :

print('error ')

print(e)

else:

print('result: ', result)

finally:

print('code that will always be executed no matter whether an exception is generated or not ')

print('Program end ')

(2) Illustration:

4. Common exception types in python

Serial numberException typedescribe
1zeroDivisionErrorDivide (or modulo) zero (all data types)
2IndexErrorThis index does not exist in the sequence
3KeyErrorThis key is not in the map
4NameErrorObject not declared / initialized (no properties)
5SyntaxErrorPython syntax error
6ValueErrorInvalid parameter passed in

5 exception handling module traceback

Use the traceback module to print exception information

#print(10/0)
import  traceback
try:
    print('----------')
    print(1/10)
except:
    traceback.print_exc()

Output results:

 

6. Debugging of pycharm development environment

(1) Breakpoint

When the program runs here, temporarily suspend and stop execution. At this time, you can observe the operation of the program in detail for further judgment

 

(2) Enter debug view

Three ways to enter the debug view

Click the button on the toolbar

 

Right click Edit area: Click: debug'module name'

Shortcut key: shift+F9

(3) After entering the debugging platform, click the down arrow to enter the next debugging step

 

Two ideas of programming: process oriented and object-oriented

Process orientedobject-oriented
differenceThings are relatively simple and can be solved by linear thinkingThings are complex and cannot be solved by simple linear thinking
common groundBoth process oriented and object-oriented are a way of thinking to solve practical problems

The two complement each other, not opposite

To solve complex problems, it is convenient for us to grasp the complex relationship between things and analyze the whole system through object-oriented method; When it comes to micro operations, the process oriented approach is still used

Classes and objects

1. 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

2. Data type

Different data types belong to different classes

Viewing data types using built-in functions

print(type (100))          <class 'int'>

print(type(99))           <class 'int'>

print(type(520))          <class 'int'>

3. Object

100, 99 and 520 are similar and different examples contained under the int class. This example is called an instance or object in the professional number language

Class creation

1. Syntax for creating classes

class  Studant :

pass

2. Composition of classes

Class properties

Example method

Static method

Class method

3. Illustration:

 

example:

class Student:   #Student is the name of the class (class name), which is composed of one or more simple characters. Each simple initial is uppercase and the rest is lowercase
    pass
#Is everything an object in python? Is there room for memory
print(id(Student))
print(type(Student))
print(Student)

Output results:

  example:

lass Student:
    nativ_pace='Jilin'   #Variables written directly in a class are called class attributes
    def __init__(self,name,age):
        self.name=name   #self is called an entity attribute. It performs an assignment operation and assigns the value of the name of the local variable to the entity attribute
        self.age=age

    #Example method
    def eat(self):
        print('The students are eating...')

        #Static method
        @staticmethod
        def method():
            print('I used it statticmethod So I'm a static method')

#Functions defined outside a class are called methods defined inside a class

def drink():
    print('drink water')

Object creation

1. Object creation is also called class instantiation

2. Syntax:

Instance name = class name ()

3. Example:

#Create an instance object of the Student class

stu=Student(' Jack', 20)

print(stu.name).     # Instance properties

print(stu.age)     # Instance properties

stu.info()         # Example method

Meaning: with an instance, you can call the content in the class

4. Illustration:

  example:

class Student:
    nativ_pace='Jilin'   #Variables written directly in a class are called class attributes
    def __init__(self,name,age):
        self.name=name   #self is called an entity attribute. It performs an assignment operation and assigns the value of the name of the local variable to the entity attribute
        self.age=age

    #Example method
    def eat(self):
        print('The students are eating...')

    #Static method
    @staticmethod
    def method():
        print('I used it statticmethod So I'm a static method')   
#Class method
    @classmethod
    def cm(cls):
        print('I'm a class method because I use classmethod Modify')

     
#Functions defined outside a class are called methods defined inside a class

def drink():
    print('drink water')


#Create object of Student class
stu1=Student('Zhang San',20)
print(id(stu1))
print(type(stu1))
print(stu1)
print('----------------------------------')
print(id(Student))   #Student is the class name
print(type(Student))
print(Student)

#Call method
stu1.eat()
print(stu1.name)   #Object name. Method name ()
print(stu1.age)

print('---------------')
Student.eat(stu1)    #The function of line changing code is the same as stu1.eat(), that is, there are two calling methods
#Class name. Method name (class object) - "is actually self at the method definition

Output results:

 

Class attribute, class method, static method

1. Class attribute: variables outside the methods in the class are called class attributes and are used by all objects of the class

Shared

2. Class method: a method decorated with @ classmethod and accessed directly by class name

3. Static method: the main method modified with @ staticmethod and the method accessed directly with the class name

print(Student.native_place).. # access class properties

student.cm(). # call class method

Student.sm(). # call static method

example:

class Student:
    nativ_pace='Jilin'   #Variables written directly in a class are called class attributes
    def __init__(self,name,age):
        self.name=name   #self is called an entity attribute. It performs an assignment operation and assigns the value of the name of the local variable to the entity attribute
        self.age=age

    #Example method
    def eat(self):
        print('The students are eating...')

    #Static method
    @staticmethod
    def method():
        print('I used it statticmethod So I'm a static method')
    #Class method
    @classmethod
    def cm(cls):
        print('I'm a class method because I use classmethod Modify')
#How to use class properties
stu1=(Student('Zhang San',20))
stu2=Student('Li Si',30)
print(stu1.nativ_pace)
print(stu2.nativ_pace)
Student.nativ_pace='Tianjin'
print(stu1.nativ_pace)
print(stu2.nativ_pace)
print('-----------How class methods are used--------------')
Student.cm()
print('-----------How static methods are used--------------')
Student.method()

Output results:

 

Dynamic binding properties and methods

1. Python is a dynamic language that can dynamically bind properties and methods after creating objects

def show ():

print('I am a function ')

stu=Student (' Jack', 20)

stu.gender = "male"      # Dynamic binding gender

print(stu.name,stu.age, stu.gender)

stu.show=show    # Dynamic binding method

stu. show()

2. Illustration

  3. Examples of corresponding diagrams:

lass 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(id(stu1))
print(id(stu2))
print('-------------------by stu2 Dynamically bind gender attributes-------------')
stu2.gender='female'
print(stu1.name,stu1.age)
print(stu2.name,stu2.age,stu2.gender)

print('----------------Dynamic binding method--------------------')


def show():
    print('Defined outside the class, it is called a function')

stu1.show=show()   #The method must be bound before it can be called
stu1.show

Output results:

  Three characteristics of object oriented

1. Encapsulation: improve program security

(1) Wrap data (properties) and behavior (Methods) into class objects. Operate on properties inside the method and call methods outside the class object. In this way, you don't need to care about the specific implementation details inside the method, thus isolating the complexity.

(2) 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 two "two" are used in front.

2. Inheritance: improve code reusability

3. Polymorphism: improve program scalability and maintainability

4. Packaging example:

lass Student:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def show(self):
        print(self.name,self.__age)

stu=Student('Zhang San',20)

#Use name and age outside the class
print(stu.name)
# Print (stu. Age) will report an error after running, because meeting means that it is not seen outside the class

5. Inherit

(1) Syntax format

Class subclass class name (parent class 1, parent class 2..):

pass

(2) If a class does not inherit any classes, it inherits object by default

(3) Python supports multiple inheritance

(4) when defining a subclass, the constructor of the parent class must be called in its constructor.

example:

lass 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,teachofyear):
        super().__init__(name,age)
        self.teachofyear=teachofyear


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

stu.info()
teacher.info()

Output results:

 

(5) Multiple inheritance examples:

class  A(object):
    pass
class B(object):
    pass
class C(A,B):
    pass

6. 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

In the overridden method of a subclass, you can call the overridden method in the parent class through super().xxx()

example:

class Person(object):   #The Person class inherits the object 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,teachofyear):
        super().__init__(name,age)
        self.teachofyear=teachofyear

    def info(self):    #Method rewrite
        super().info()
        print('Teaching age',self.teachofyear)


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

stu.info()
teacher.info()

print('------------Method rewrite---------')
teacher.info()

Output results:

  7. object class

The. Object class is the parent class of all classes, so all classes have the properties and methods of the object class. · the built-in function dir() can view all the properties of the specified object

. Object has a _str_ () method to return a description of the Object, which corresponds to the built-in function. str() is often used in the print() method to help us view the information of the Object, so we often rewrite _str_ ()

example:

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

    def __str__(self):
        return 'My name is{0},this year{1}year'.format(self.name,self.age)
stu=Student('Zhang San',20)
print(dir(stu))
print(stu)   #Methods such as _str_ () are called by default
print(type(stu))

8. Polymorphism

In short, 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 method in the object to call according to the type of object referenced by the variable.

The difference between static language and dynamic language about polymorphism:

① Three necessary conditions for static language implementation (Java is a static language) polymorphism:

inherit

Method rewrite

A parent class reference points to a child class object

② The polymorphism of dynamic language (python is a dynamic language) advocates "duck type". When you see a bird walking like a duck, swimming like a duck, and putting it away like a duck, the bird can be called a duck. In duck type, you don't need to care about what kind of object is, whether it is a duck or not, but only about the behavior of the object.

example:

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()

#Start calling function
fun(Cat())
fun(Dog())
fun(Animal())
print('-------------------')
#Person has no inheritance relationship with Animal, Cat and Dog, but because person also has eat method, it will also call eat method
fun(Person())

Output results:

  9. Special properties and methods

namedescribe
Special properties_dict_Gets a dictionary of all properties and methods bound to a class object or instance object
Special method_len_()_Len_ () method, so that the parameters of the built-in function len() can be user-defined types
add_()By overriding the _add_ () method, you can use a custom object with the "+" function
_new_()Used to create objects
_init_()Initialize the created object

Examples of special attributes:

class A:
    pass
class B:
    pass
class C(A,B):
    def __init__(self,name,age):
        self.name=name
        self.age=age

#Create class C objects
x=C('Jack',20)  #x is an instance object of type C
print(x.__dict__)   #Attribute dictionary of instance object
print(C.__dict__)   #If it is a class object, you will see its properties and methods
print('-------------------')
print(x.__class__)   #< class' _main_. C '> output the class to which the object belongs
print(C.__bases__)  #Parent type element of class C
print(C.__base__)   #The nearest parent type element in the output parameter
print(C.__mro__)  #Class hierarchy
print(A.__subclasses__()) #List of subclasses

Output results:

 

Examples of special methods:

a=20
b=100
c=a+b  #Addition of two integer type objects
d=a.__add__(b)  #The results are exactly the same

print(c)
print(d)


class Student:
    def __init__(self,name):
        self.name=name
    def __add__(self, other):
        return self.name + other.name

    def __len__(self):
        return len(self.name)


stu1=Student('Zhang San')
stu2=Student('Li Si')

s=stu1+stu2  #It implements the addition operation of two objects (because the method of _add_ () is written in the Student class, an error will be reported if it is not written directly)
print(s)
#Or another implementation
s=stu1.__add__(stu2)

print('--------------------------')
lst=[11,22,33,44]
print(len(lst))  #Len is the built-in function len, which is used to calculate the length
print(lst.__len__())
#print(len(stu1))  #If you use it directly, an error will be reported. If you have to output it, you need to write the len () method

Output results:

 

Examples of special methods:

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __new__(cls, *args, **kwargs):
        print('__new__Called to execute, cls of id Value is{0}'.format(id(cls)))
        obj=super().__new__(cls)
        print('Of the object created id Is:{0}'.format(id(obj)))
        return  obj

    def __init__(self,name,age):
        print('__init__Called, self of id The value is:{0}'.format(id(self)))
        self.name=name
        self.age=age

print('object Of this class object id Is:{0}'.format(id(object)))
print('Person Of this class object id Is:{0}'.format(id(Person)))

#Create an instance object of the Person class
P1=Person('Zhang San',20)
print('P1 this Person Class id: {0}'.format(id(P1)))

Output results:

  Illustration and step description of operation:

 

10. Shallow and deep copies of classes

(1) Assignment of variables

It just forms two variables, which actually point to the same object

(2) Shallow copy

  Python copy is generally a shallow copy. When copying, the sub object content contained in the object is not copied. Therefore, the source object and the copy object will reference the same sub object

(3) Deep copy

Use the deepcopy function of the copy module to recursively copy the sub objects contained in the object. All sub objects of the source pair fog and the copy object are also different

(4) Example of variable assignment:

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

#(1) Assignment of variables
cpu1=CPU()
cpu2=CPU()
print(cpu1)
print(cpu2)

Output results:

  Result analysis diagram:

  Example of shallow copy

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

#(1) Assignment of variables
cpu1=CPU()
cpu2=CPU()
print(cpu1)
print(cpu2)

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

#Shallow copy
import  copy
computer2=copy.copy(computer)
print(computer,computer.cpu,computer.disk)
print(computer2,computer2.cpu,computer2.disk)

  Analysis diagram:

  Examples of deep copy:

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

#(1) Assignment of variables
cpu1=CPU()
cpu2=CPU()
print(cpu1)
print(cpu2)

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

#Shallow copy
import  copy
computer2=copy.copy(computer)
print(computer,computer.cpu,computer.disk)
print(computer2,computer2.cpu,computer2.disk)

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

Illustration:

  modular

1. Module

Modules in English

2. Relationship between function and module

A module can contain N more functions

3. In Python, a file with the. py extension is a module

4. Benefits of using modules

Facilitate the import and use of other programs and scripts

Avoid conflicting function and variable names

Improve code dimensionality

Improve code reusability

5. Custom module

(1) Create module

Create a new. py file. Try not to have the same name as the standard module of Python

(2) Import module

Import module name [as alias]

From module name import function / variable / class

(3) Module import (self created module)

 

 

You can also directly use from import, which can be used directly after import

(4) Run in the form of main program

The definition of each module includes a variable _name that records the module name. The program can check the variable 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. The value of the _name variable of the top-level module is _main_

if_name_ = '__main_' :

pass

6. Packages in Python

(1) Package is a hierarchical directory structure, which organizes a group of modules with similar functions in a directory

(2) Function:

Code specification

Avoid module name conflicts

(3) Difference between package and directory

The directory containing the _init_.py file is called a package

The directory usually does not contain the _init_.py file

(4) Import of packages

import package name. Module name

 

  7. Content module for warehouse 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 date related functions
urllibStandard library for reading data from the Internet (server) j
json

Used to serialize and deserialize objects using JSON

reUsed to perform regular expression matching and substitution in strings
mathProvides a standard library of standard arithmetic operation functions
decimalDecimal operation for precise control of operation accuracy, significant digits and rounding operation
logging   It provides a flexible function to record events, errors, warnings, debugging information and other target information

Installation and use of third modules

Under cmd, enter pip install + the module to be installed, and then wait for a while. If the program does not report an error, it means that the installation is successful

 

  Coding format

Common character encoding formats

  The Python interpreter uses Unicode (memory)

py files are stored on disk using UTF-8 (external storage)

 

File reading and writing

Reading and writing principle of documents

  File read / write operation

  Common file opening modes

1. Type of file

According to the organization form of data in the file, the file is divided into the following two categories

(1) Text file: it stores ordinary "character" text. The default is unicode character set, which can be opened by Notepad program

(2) 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 bottom of the file
aOpen the file in append mode. If the file does not exist, it will be created, and the file pointer will be at the beginning of the file. If the file exists, the content will be appended at the end of the file, and the file pointer will be at the end of the original file
bOpening a file in binary mode cannot be used alone. It needs to be used 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 for file objects

Method nameexplain
read([size])Read the contents of size bytes or characters from the file and return. If [size] is omitted, it will be read to the end of the file, that is, all contents of the file will be read at one time
readline()Read a line from a text file
readlines()Each line in the text file is treated as an independent string object, and these objects are returned in the list
write(str)Writes the string str contents to a file
writelines(s_list)List string s_list writes to a text file without adding line breaks
seek(offset[, whence])

Move the file 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 represent different meanings:

0: calculate from 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 to the file, close the file and release the file object

with statement

1. 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

  example:

 

 

  The third figure implements the methods of enter and exit, so it is called the context manager

Operation directory

os module is Python's built-in module related to operating system functions and file system. The execution results of statements in this module are usually related to the operating system. Running on different operating systems may get different results.

OS module and os.path module are used to operate 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
makedirs(path1/path2.. . [, mode])Create multi-level directory
removedirs(path1/path2.. . . . .)Delete multi-level directory
rmdir(path)Delete directory
chdir(path)Set path to the current working directory

os.path module operation directory related functions

functionexplain
abspath(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, False is returned

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

 

Tags: Python

Posted on Fri, 24 Sep 2021 11:28:58 -0400 by rajivgonsalves