current position:Home>With "Python" advanced, you can catch all the advanced syntax! Advanced function + file operation, do not look at regret Series ~

With "Python" advanced, you can catch all the advanced syntax! Advanced function + file operation, do not look at regret Series ~

2021-08-23 09:35:53 It's dream

️「Python」 Advanced , Catch all the high-level grammar ! Don't look at regret series ~

 Insert picture description here


Hello, Hello, my name is Dream ah , An interesting Python Blogger , A little white , Please go easy on me
CSDN Python New star creators in the field , Author Zhou Bang NO.24 , Sophomore reading
Introductory notes : This paradise never lacks genius , Hard work is your final ticket !
Last , May we all shine where we can't see , Let's make progress together
“ Ten thousand times sad , There will still be Dream, I've been waiting for you in the warmest place ”, It's me ! Ha ha ha ~

Advanced functions

1. Time function

stay Python in , There are usually several ways to express time :
(1) Time stamp ;
(2) Formatted time string ;
(3) time tuples (struct_time).
1. Generally speaking , Time stamp It means from 1970 year 1 month 1 Japan 00:00:00 Start offset in seconds .

import time;  #  introduce time modular 
ticks = time.time()
print(" The current timestamp is :", ticks)

2. We can use time Modular strftime The method is to Format date .

import time
#  Format as 2016-03-20 11:45:39 form 
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

 Insert picture description here  Insert picture description here
3. return struct_time The main functions of are gmtime()、localtime() and strptime(),struct_time Tuples .

2. Calendar function

1.calendar.calendar(year,w=2,l=1,c=6)
Returns the year Annual calendar ,3 Month and row , The interval is c. The daily width interval is w character . The length of each line is 21* W+18+2* C.l Is the number of lines per week .

import calendar
print(calendar. firstweekday())
print(calendar.isleap(2018))
print(calendar.calendar(2021,w=1,l=1,c=6))

Then we can get our date table , Is it very nice:
 Insert picture description here
2. Returns the setting of the start date of the current week . By default , First load caendar Module returns 0, Monday .

calendar. firstweekday()

3. If it's a leap year, return True, Otherwise false.

calendar.isleap(year)

4. Back in the Y1,Y2 The total number of leap years between two years .

calendar.leapdays(y1,y2)

5. Returns the year year month Monthly calendar , Two line headings , A Monday trip . The daily width interval is w character . The length of each line is 7* w+6.l Is the number of lines per week .

print(calendar.month(2021,2,w=2,l=1))

 Insert picture description here
6. Returns a single nested list of integers . Each sublist load represents an integer for a week .Year year month All dates outside the month are set to 0; The days in the range are indicated by the day of the month , from 1 Start .

calendar.monthcalendar(year,month)

 Insert picture description here
7. Returns two integers . The first is the date code of the day of the week of the month , The second is the date code of the month . Day from 0( Monday ) To 6( Sunday ); Month from 1 To 12.

calendar.monthrange(year,month)

8.calendar.prcal(year,w=2,l=1,c=6)
amount to print(calendar.calendar(year,w,l,c))

3. Random number function

1.random.random()
Used to generate a 0 To 1 The number of random characters of : 0 <= n < 1.0.

import random#  Generate the first random number 
print("random():", random.random())#  Generate the second random number  
print("random():", random.random())

2.random.uniform(a,b)
return a,b Between random floating-point numbers , Range [a,b] or [a,b] It depends on To the nearest ,a Not necessarily better than b Small .
3.random.randint(a,b)
return a,b Integer between , Range [a,b], Be careful : The passed in parameter must be an integer ,a Be sure to than b Small .
4.random.randrang([start], stop[, step])
Returns an integer with an interval , You can set step. Only integers can be passed in ,random.randrange(10, 100, 2),
The result is equivalent to from [10, 12, 14, 16, … 96, 98] Get a random number in the sequence .
5.random.choice(sequence)
from sequence( Sequence , It's an ordered type ) Get an element at random , list 、 Tuples 、 All strings belong to sequence.

random.randrange(10,100,2) 
# The result is equivalent to 
random.choice(range(10,100,2)

6.random.shuffle(x[,random])
Used to disorganize the elements in the list , Commonly known as shuffle .

p = ["Python","is", "powerful","simple”]  
random.shuffle(p)  

7.random.sample(sequence,k)
Get... Randomly from a specified sequence k Elements returned as a fragment ,
sample Function does not modify the original sequence

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
slice = random.sample(list, 5) 
print(slice) 
print(list)

Closure and Decorator

1. Closure :

Python Functions support nesting . If you scope an external function in an internal function ( Non global scope ) The variables are quoted , Then the inner function will be called closure . Closure Need to satisfy the following 3 Conditions :

  1. Exists in two nested functions , And closures are internal functions ;
  2. The inner function references the variables of the outer function ( Free variable );
  3. The external function will return the function name of the internal function .

 Insert picture description here

def outer(start=0):
    count=[start]
    def inner():
        count[0]+=1
        return count[0]
    return inner
out = outer(5)
print(out())

2. Decorator :

Suppose we have developed an existing function , Subsequent may increase temporary demand , For example, insert logs , We can add a wrapping function , It is responsible for these additional requirements , This wrapping function is Decorator .

Decorators are mainly used in the following scenarios :

  1. Introducing logs ;
  2. Function execution time statistics ;
  3. Prepare for function execution ;
  4. Clean up after function execution ;
  5. Permission to check ;
  6. cache .

Decorator is a function , It needs to receive a parameter , This parameter represents the modified function . for example , There is one of the following Decorator function

def myDectoration(func):
    def inner():
        print(" Executing internal function ")
        func()
    return inner

def printMessage():
    print("-------- Welcome -------")
pm = myDectoration(printMessage)
pm()

The decorator is a nested function, and the inner function is a closure .
The external function receives the modified function (func)

By adding... Before the function definition @ Symbol and decorator name , Implement the wrapper of the decorator to the function . to f1 Function plus decorator , Examples are as follows :

@w1
def f1():
    print(’f1')

here , The program will automatically compile and generate the code that calls the decorator function , Equivalent to :

f1 = w1(f1)

Multiple decorators :
Multiple decorators are applied to a function , The call order is from bottom to top .

common Python Built in functions

1.map function

map The function calls... With each element in the parameter sequence function function , Save the result returned after each call as an object

func = lambda x:x+2
result = map(func, [1,2,3,4,5])
print(list(result))

flow chart :
 Insert picture description here

2.filter function

filter The filter function performs a filter operation on the specified sequence .
filter The function is defined as follows :

filter(function,iterable)

The first 1 An argument can be the name of the function ; The first 2 The first parameter represents the sequence 、 A container or iterator that supports iteration .

func = lambda x:x%2
result = filter(func, [1, 2, 3, 4, 5])
print(list(result))

flow chart :
 Insert picture description here
 Insert picture description here

File operations

1. Opening and closing of files

stay python in , Use open Method to open a file :

open( file name , Access pattern )
  • “ file name ” Must fill in
  • “ Access pattern ” It's optional

Access pattern : Insert picture description here
 Insert picture description here
All open files , Remember to use close Method to close the file :

#  Create a new file , The file named :test.txt
f = open(itheima.txt', 'w')
#  Close this file 
f.close()

2. Reading and writing of documents

Writing documents :
Write data to file , Need to use write Method to accomplish , When operating on a file , Every call write Method , The written data will be appended to the end of the file :

f = open('itheima.txt', 'w')
f.write(‘hello itheima, i am here!’)
f.close()

Reading documents :
The way 1: Use read Method to read the file

f = open('itheima.txt', 'r')
content = f.read(12)
print(content)
print("-"*30)
content = f.read()
print(content)
f.close()

The way 2: Use readlines Method to read the file

f= open('itheima.txt', 'r')
content = f.readlines()
i = 1
for temp in content:
     print("%d:%s" % (i, temp))
     i += 1
f.close()

The way 3: Use readline Method reads data line by line

f = open('itheima.txt', 'r')
content = f.readline()
print("1:%s"%content)
content = f.readline()
print("2:%s"%content)
f.close()

File location reading and writing :

f = open("itheima.txt", "r")
str = f.read(4)
print(“ The data read is  :, str)
position = f.tell()
print(" Current file location  : ", position)

3. Renaming and deleting files

os Module rename() Method to rename the file . The format is as follows :

os.rename( File name to be modified ,  New file name )

os Module remove() Method to delete a file . The format is as follows :

os.remove( File name to be deleted )

4. File related operations

1. Create folder
os Modular mkdir Method to create a folder , Examples are as follows :

import os
os.mkdir(" Zhang San ")

2. Get current directory
os Modular getcwd Method to get the current directory , Examples are as follows :

import os
os.getcwd()

3. Change the default directory
os Modular chdir Method to change the default directory , Examples are as follows :

import os
os.chdir("../)

4. Get directory list
os Modular listdir Method to get a list of directories , Examples are as follows :

import os
os.listdir (./)

5. Delete folder
os Modular rmdir Method to delete a folder , Examples are as follows :

import os
os.rmdir (” Zhang San ”)

The last little benefit to everyone : If you want to get started quickly python My friends , This is sorted out in detail PPT Can quickly help everyone to fight python Basics , You can download it if you need it Python A complete set of introductory basic tutorials + Xiaobai Express + You won't come to me !
All right. , That's all I want to share with you today
️️️ If you like , Don't be stingy with your one key triple connection ~ Insert picture description here

Voting session :

copyright notice
author[It's dream],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2021/08/20210823093548234a.html

Random recommended