The third day of Python cultivation

Source: Internet
Author: User
Tags closure function definition string format wrapper

Today mainly about the file operation, function and adorner, decorator compared to burn the brain, need to do more practice, gradually decomposition to understand! Come on! A file operation
The concept of operating system-supplied files
You can manipulate the disk.

Read-only mode of the file: Note If you want to add a R:open (r "C:\a.txt") in front of Windows. Or the delimiter is/
f = open ("D:/python21 period/l002-Old boys education-python20 VIP video-mp4/b.txt", "R", encoding= "Utf-8")
data = F.read ()
Print (data)
F.close () # file closed, recycle operating system resources
Print (f) This f variable is still present because it is a python variable. Python variables are automatically released after the program ends
F.read () This file has been shut down by the operating system, so it cannot be read.

Another approach: with open
With open ("A.txt", "R", encoding= "Utf-8")
Pass
This is to help you close the file automatically.

Other reading methods
1 f.readline () read Only one line
Print (F.readline (), end= "")
Print (F.readline (), end= "")
Print (F.readline (), end= "")

2 readlines () The files are all read out and placed in a list of lists.
Note: If the file is too large, such as a 1T file cannot be manipulated, this only applies to small files


Write-only mode of the file: the default is wt text write, if the file does not exist on the creation of files, if there is a file to empty the original file!!
f = open ("B.txt", "W", encoding= "Utf-8")
F.write (1111\n)
F.write (222222\n)
F.close ()

Other ways to write:
1 f.write ("11111\n")

2 F.writelines can be written to a file in the form of a list or in the form of a meta-ancestor.
F.writelines (["name\n", "age\n", "Hobbie"])
The result is
Name
Age
Hobbie
########## Note If the WT text format is open, then only the string format can be written


1 File Processing
Add
Print (F.writable ()) to see if it is writable writable returns true not writable false
New Write mode:
A append mode, append write to the end of the file
f = open ("B.txt", "a", encoding= "Utf-8") file does not exist on the new one, if it exists, open the file bar cursor moved to the end of the file append write, the original file content does not affect

If you read multiple lines, you can use the for
Whit open ("A.txt", "R", encoding= "Utf-8") as F:
For line in F:
Print (line)

b mode can be understood as binary
RB Binary Read
With open ("A.txt", "RB") as F:
Print (F.read (). Decode ("Utf-8") # # # If the text content is also saved as B binary mode, you can use decode decoding to view the text

WB Binary Write
With open ("A.txt", "WB") as F:
res = "Add". Encode ("utf-8") binary writes need to be encoded for binary write
F.write (RES)

AB Append Write
The same as above is required encode ("Utf-8")

Practice Implement the CP command to copy any type of file
Import Sys
_,src_file,dst_file = sys.argv # SYS.ARGV is the parameter that gets run, the first one is the cp.py program file The second is the source file, the third is the destination file,
# so the first one without getting, _, you can empty the first parameter, Src_file is the second parameter source file
# Dst_file is the third parameter of the destination file.
With open ("Src_file", "RB") as Read_f, open ("Dst_file", "WB") as Write_f:
For line in Read_f:
Write_f.write (line)
# Note the memory data to the hard disk to save recommendations set a buffer, accumulate a certain size monkeys write to disk, reduce IO pressure
# Wirte_f.flush () This is telling the operating system to write to the disk quickly.

Changes to the file:
Import OS
With open ("1.txt", "R", encoding= "Utf-8") as Read_f,open (". 1.txt.swap", "W", encoding= "Utf-8") as Write_f:
data = Read_f.read ()
Write_f.write (Read_f.replace ("Alex", "SB"))
Os.remove ("1.txt")
Os.rename (". 1,txt.swap", "1.txt")
This is it. The entire file is written to the in-memory modification, and if the file is too large, it causes stuttering, so you can change it one line at a line:
For I in Read_f:
If "Alex" in I:
i = I.replace ("Alex", "SB")
Write_f.write (i)

Cursor movement within the file
There is only one situation where the cursor refers to moving in a character unit
With open ("C.txt", "RT", "") as F:
F.read (3)
Only the Read method can be moved by character
Print (F.tell) tells the cursor the first few bytes. Note that if you have Chinese, a Chinese is 3 bytes. Like what
Hello, hi.
F.read (6)
Print (F.tell ())
The result is 8 because an English is a byte, Chinese is three bytes so when I read the sixth character, the cursor is on the 5+3=8 byte.

The movement of the cursor
F.seek
With open ("A.txt", "RT", encoding= "Utf-8") as F:
F.read (6)
Print (F.tell ())
This time the cursor has moved to the 6th character (8th byte)
F.seek (8,0) # The first parameter is to move a few bytes, the second parameter has three modes: 0,1,2. 0 represents the relative position reference, starting at the beginning of the file
# Seek (8,0) is moved from beginning 0 to move backwards by 8 bytes.
# 0 mode can be used in both character T mode and binary B mode. An additional 1 2 mode is required to be used in bytes mode. Their moving units are all bytes.
Print (F.read ())
The result is to print the contents after the first 8 bytes.

1 mode:
Moves backwards from the current cursor.
F.read (6) # has moved 6
F.seek (2,1) # from the current 6th cursor continue to move backward 2
Print (F.read ())
The result is a 6+2 byte, and also the content after the 8th byte is printed.

2 mode:
Start moving from the end of the file for reference. Move backwards.
F.seek ( -3,2)
Print (F.read ())
Move 3 bytes from the end of the file, and if the file is finally a Chinese, just print this Chinese

Implement Tail-f Access.log
With open ("Access.log", "RB") as F:
F.seek ()
While True:
line = F.readline ()
If line:
Print (line)
Else
Time.sleep (0.5)
Note Binary b mode does not translate \ n newline characters. Character T mode translation \ n If the text content has \ n line break, binary B mode print (Line.decode (), end= "")
End= "" is to remove the space that comes with print. If there is no line break in the text content, use print directly.


Truncate file
Truncation mode can only be used in a mode:
With open ("A.txt", "a", encoding= "Utf-8") as F:
F.truncate (3) # only from the beginning of the file as a reference. 3 for interception of 3 bytes
#就是只截断前三个字符



2 functions
1 Function Basics
Why use a function? There's no problem with the function.
1 organizational structure is not clear, poor readability
2 Code Redundancy
3 Poor scalability

What is a function?
A tool--function with one function
A function is a pre-prepared tool.
The tools are ready, so you can use them. Re-use
Defined first, then called.

The classification of functions?
Built-in functions:
Help (function name) This is the comment information under the View function reference Syntax 1
Len
Max
Mix
Count
Custom functions: Def custom functions
Defining functions
Grammar:
def function name (parameter 1, parameter 2):
"" "Note Information" "" # Optional
function body, function body
return value
(The function is actually a variable, but it can be called)
So the execution function is divided into two steps, the first step is to find the function variable by the function name, and find the function can be called with ().
Definition phase:
The definition function only detects whether the syntax is a problem and does not define the code.

Call Function:
Called after the definition is first defined.
Call the function, if the function is defined in the variables and other functions or other problems will be an error.
Liezi:

def foo ():
Print (' from foo ')
Bar ()
Foo ()
The first call is problematic because the bar function is undefined, so a bar function needs to be defined
def bar ():
Print ("From Bar")
Foo ()
It will be all right this time. Note that the call principle is defined first.

Define the three forms of a function:
1: no parameter function
def foo ()
Print ("I am a parameterless function")
2: Parametric function
def auth (u,p):
if u = = "Root" and P = = "123":
Print ("Login successfull")
Else
Print ("User or password Err")
def Interactive ()
Name = input ("Please enter account:"). Strip ()
Password = input ("Please enter password:"). Strip ()
Auth (Name,password)
3: Empty function
def auth ():
Pass
When writing an application, define a function for each function. An empty function is the first frame. Stand in a position.

The return value of the function:
# there can be multiple return within a function but only one return is executed.
def foo (x, y)
Print ("First")
Return 1
Print ("second")
Return 2
Print ("third")
Return 3
Res=foo ()
The print (RES) result is first 1 because execution encounters a return and exits. Run the program first, and then return the value in the output

# executes the return function and ends immediately, and returns the value as the result of this call.
def foo (x, y):
Retrue X+y
res = foo (ON)

Functions can be returned:
def bar ();
Print ("From Bar")
def foo ():
Return Bar ()
Print (foo ())

There is no return, no returns, none returned. Print (foo) is the printing function memory address, and print (foo ()) is the return execution result
Returns a value of return, which returns the value itself.
Return multiple values Returns a meta-ancestor format.

Three types of function calls:
def my_mix (x, y):
If x >=y:
return x
Else
Reture y
The first type: use alone
Res1 = My_max
The second type: The result of the function return value is calculated
Res2 = My_max (*10)
Third: A function call can be used as a parameter to another function
Res3 = foo (My_max (), AA)

Use of function parameters
1. Parameter type: Two kinds of
The 1 parameter def foo (x, y) is a formal parameter within the parentheses during the definition phase and the parameter is not a memory space during the definition phase.
2 argument foo () the value passed in the parentheses in the call phase is called an argument, which is equivalent to the value
At the call stage, the value of the argument is bound to the parameter and unbound after the call ends.
2. Position parameters
Parameters that are defined in order from left to right.
1 Positional parameters: must be passed the value, one less one can not.
2 positional arguments: corresponds to parameter one by one.
def foo (x, y)
Print (x, y)
Foo (y=1,x=1)
3. Keyword parameters
When a function is called, an argument that is defined in the form of a key=value
Features: Named to the parameter value, no longer dependent on the location
Attention:
def foo (name,age,sex):
Print (Name,age,sex)
Note: The 1 keyword argument must be behind the positional argument.
2 You cannot assign multiple values to the same parameter.

4. Default parameters
1 refers to a parameter that is already duplicated in the function definition phase.
def foo (x,y=1):
Print (x, y)
The advantage of the default parameter is that you can change the value of the default parameter by not passing the value.
2 The value of the default parameter is copied only once when it is defined
res = 1
def foo (x,y=res):
Print (x, y)
res = 10
Foo ("AAAA")
The result is "AAAA" 1
3 The value of the default parameter should usually be an immutable type. It's either a number or a ganso.

5. Variable length parameter *args, **kwargs
When calling a function, the argument is worth the number not fixed
The arguments are in the form of positional arguments and keyword arguments.
That is, the number of lengths in the two form of the argument is not fixed.
Solutions for formal Parameters: * and * *
* is the location argument solution
* * is the keyword key value solution
1 *args
The location of the actual participants saved as Ganso form
def foo (x,y,*z):
Print (x, y)
Print (z)
Foo (1,2,3,4,5,6)
The result is, 1 gives x 2 to Y * receives the back and then assigns the value to the z3,4,5,6 in the form of the ancestor to Z
The
(3,4,5,6)
Another kind
def foo (x, y):
Print (x, y)
Foo (* ())
The result is
2 **kwargs
def foo (X,y,**kwargs):
Print (x, y)
Foo (x=1,y=2,i=3,l=4)
This situation * receives i=3,l=4 and assigns values to Kwargs to be saved as a dictionary format.
Another kind
def foo (X,y,**kwargs)
Foo (y=2,**{"C": 5, "B": 6, "X": 2})
3 Application Scenarios
def bar (x, Y, z):
Print (x, y, z)
def wrapper (*args.**kwargs):
Bar (*args,**kwargs)
Wrapper (1,2,3,a=1,b=2,c=2)
This will cause an error, because the wrapper receives the parameter, passes it to bar, and then bar passes * and * * with the parsed back
The bar will give an error when the parameter is passed to wrapper at the beginning. Cannot assign a value.

6. Named keyword parameters
Refers to the parameter defined in the *, which must be passed (unless he has a default value), and must be passed in the form of Key=value.

Three-function step
(1) Name space:
1 namespaces
2 Local namespaces
3 Built-in namespaces

1 name space, or namespace
Run-time, which is stored in the relationship between the variable and the value memory address

2 temporary namespaces
Like defining a function.
def func ():
Name = "Wustr"
Age = 23
The function name is stored in the memory space
But the variables in the function body are not tubes.
When the function is executed, he will find the variable inside the function body through the function name and
Temporarily creates a memory space, which is a temporary namespace, also called a local name space, and then
The variables inside the function are stored in the temporary namespace.
Then, as the function executes, the memory of the temporary namespace disappears. Release.

3 Built-in namespaces
As long as the py file interpreter is created, the built-in namespace is loaded into memory. The built-in functions can be used
For example: Len ()

(2) Scope:
1 Global scope: Global namespaces, built-in namespaces
2 Local scope: local namespace

(3) Load order, order of values
Load order: The built-in namespaces are loaded into memory first. The global namespace is then loaded into memory, and finally the local namespace (only loaded when the function executes)
Order of Values:
The function takes a value from the local scope first, and if no global scope is found, the built-in namespace is not found. That is to find out from within.
And it's just one-way, to find the last No.

Globals locals built-in functions
Globals to print the global namespace
Locals print the local namespace

Global nonlocal Keywords
Global
A variable that can use a global namespace inside a function. But it can't be changed. If you want to change the need to declare global variables using the Global keyword

Nonlocal declares global variables, and changes global variables if they exist.
References and changes the local variables of the previous layer. The variables on the same layer in the previous layer will change.


(4) Function name:
1 can be assigned to each other
Def fun1 ():
Print (666)
F1 = func1
F1 ()

2 can be used as a function parameter
Def FUNC2 ():
Print (111)
def func3 (argv):
ARGV ()
Print (222)
FUNC3 (FUNC2)

3 parameters that can be used as container class data types
Def func11 ():
Print (222)
Def FUNC22 ():
Print (333)
Def func33 ():
Print (444)
ll = ["Func11", "Func22", "Func33"]
For I in LL:
I ()

4 can be used as the parameter and return value of a function
def func ():
Print (666)
def func1 (argv)
Print (777)
Return argv
res = FUNC1 (func)
Res ()

(5) Closures:
A reference to a non-global variable of the outer layer function of the inner layer function
def wrapper ():
Name = "Alex"
def inner ():
Print ((name)
Inner ()
Wrapper ()

Determine if the closure is inner.__closure__
If return cell is not returned none
The advantage is that if Python detection is a closure. There is a mechanism where your local scope does not end with the end of the function.
such as reptiles, crawling down the data, using closures can climb down the data saved to memory, the next crawl directly from memory to take
Import Urlopen,url
def index ():
url = "Http://www.xiaohua100.com/index.html"
Def get ():
return Urlopen (URL). Read ()
return get
Index () ()
Four-decoration device
    Function object
A function is the first class of objects: Refers to functions that can be passed as data
1 can be referenced x=1,x=y
def func (x, y):
Print (x, y)
F=func
F (+)

2 can be passed as arguments to a function
def foo ():
Print ("Form foo")
def bar (x):
X ():
Bar (foo)
3 can be used as the return value of a function
4 elements that can be used as container types

Later content to be mended ...

The third day of Python cultivation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.