Python Learning Note III (file operations, functions)

Source: Internet
Author: User
Tags ldap wrapper

First, file processing 1, File open mode

Open the mode of text, by default add T, you need to write or read the encoding case to add the encoding parameter.

R Read-only mode, default mode, file must exist, cannot exist then report an exception.

W Write-only mode, if the file does not exist, it is created, if the file already exists then empty the content, can not read the file.

A append mode, the file does not exist is created, if the file already exists at the end of the file appended, can not read the file.

Open non-text mode, use "B" to indicate that the read and write bytes are required, and the encoding cannot be specified. Mainly have RB, WB, AB three models.

2. Operation File Method

Read file

With open (' Test.txt ', ' R ', encoding= "UTF-8") as F:    print (F.read ())          #读取文件全部内容with open (' Test.txt ', ' R ', encoding= "UTF-8") as F:    print (F.readlines ())  # reads the contents of each line of the file, depositing the list with open (' Test.txt ', ' R ', encoding= "UTF-8" As f:    print (F.readline ())  # reads a file line with open (' test.txt ', ' RB ') asF:    print (F.read ())          # BYTE read mode reads the entire contents    of the file

File Write

With open (' Test1.txt ', ' W ', encoding= "UTF-8") as F:    f.write ("Hello world!\n")  #文本模式, add line break with open (' Test1.txt ', ' W ', encoding= "UTF-8") as F:    f.writelines (["hello\n", "world\n"])  #文本模式, add line breaks with open (' Test1.txt ', ' WB ') as F:    f.write ("Hello World". Encode ("Utf-8"))  #b模式需对字符先编码with open ("Test1.txt", ' WB ' as F:    f.writelines (["hello\n". Encode ("Utf-8"), "world\n". Encode ("Utf-8")]) #b模式需对字符串手动编码 

Other operations

Import TIMEF = open ("Test1.txt", ' W ', encoding= "UTF-8") #b模式没有encodingprint (F.writable ()))   #文件是否看可写print ( F.readable ())   #文件是否可读f. Write ("AA") F.flush ()    #立刻将文件内容从内容刷入硬盘time. Sleep (5) f.close ()       #文件关闭, When no flush is turned off, the contents of the file are not brushed into the drive  
3. Cursor movement within the file

1.read (3)

When the file is opened as text, the delegate reads three characters.

When the file is opened in B, the delegate reads three bytes.

2. In addition to read, the other file cursor movement is in bytes, into the Seek,tell,truncate

With open ("Test.txt", ' R ', encoding= "UTF-8") as F:    F.seek (4,0)   #第一个参数表示移动的相对位置, the second parameter is 0 to move to the beginning of the file, 1 represents the current position, 2 represents the move to the end of the file    print (f.read ())    print (F.tell ())  #返回光标当前位置, executed as read () after the end of the file # Truncate to truncate the file, the file must be writable, not use W or w+ mode, the file will be emptied, it is recommended to use r+ or a or a + mode with open ("test.txt", ' r+ ', encoding= "UTF-8") as F:    F.truncate (7)    #截取前7个字节的内容. 
4. Modification of documents

Mode one, the file is read from the hard disk into memory, in memory after the modification, after writing a new file, replace the original file. The file is stuck when it is too large to read into memory.

Import Oswith Open ("Test.txt", ' R ') as Read_f,open (". Test.txt.swap", ' W ') as Write_f:    data = Read_f.read    data = data.replace ("xxx", "eee")   #字符不可变 to be re-assigned to data    write_f.write (data) os.remove ("Test.txt" ) Os.rename (". Test.txt.swap", "test.txt")    

Mode two, each line of the file read into the memory, modified by the line, modified after the completion of the new file, complete and replace the original file.

Import Oswith Open ("Test.txt", ' R ') as Read_f,open (". Test.txt.swap", ' W ') as Write_f: For line in     read _f:        if "xxx" in line: line            = line.replace ("xxx", "eee")        Write_f.write (line) Os.remove (" Test.txt ") Os.rename (". Test.txt.swap "," test.txt ")     

Second, function basis

The purpose of using the function: To solve the problem of unclear code organization structure, poor readability, reduce code redundancy, reduce maintenance difficulty, improve scalability.

Functions are mainly divided into built-in functions and custom functions.

1. function definition and invocation

Defining functions

#语法def Function name (parameter 1, parameter 2, Parameter 3,...):        The value returned by the "comment" function body return # function name to reflect its meaning  

The principle used by the function is: first define and then use

The function detects only the syntax in the definition phase, does not execute code, and cannot discover logic errors in the code.

2. Parameters of the function

positional parameters: parameters defined in order from left to right.

Positional parameters: Required parameter

Positional arguments: Pass values to parameters by location

keyword parameter: A parameter defined as a key-value pair.

Argument and formal parameter positions do not have to be one by one corresponding

The keyword argument must be on the right side of the positional argument

Cannot repeat a value for the same parameter

    Default parameters: The parameter is assigned when it is defined

Can be passed the value can also not pass, often need to change the parameters defined as positional parameter, the change is small defined as the default parameter

is only assigned once at the time of definition and is immutable type

The default parameter is defined to the right of the position parameter

    Variable length parameter: The number of argument values is not fixed

    Using *args to receive positional arguments, use **kwargs to receive the key arguments, and the arguments must be passed in the form of a keyword argument.

def func (*args,**kwargs):    print(Args,kwargs) func (3,4,5,66,a=33,b= "ASF", c=222)   # The previous positional argument is received by the args as a tuple, and the following key arguments are Kwargs in a dictionary 
def func (x,y,*args,a=1,b,**Kwargs): Print (    x, y)    print (args) print (    a)    print (b)    print(Kwargs) func (1,2,3,4,5,b=3,c=4,d=5)     

 

Three, function object, function nesting, namespace and scope, adorner 1. Function Object Features:

Can be referenced

Can be passed as a parameter

The return value can be a function

Elements that can be treated as container types

def func1 ():    print ("from func1")    return func2      #返回func2def func2 ():    print ("from Func2 ") List = []list.append (Func1 ())  #返回func2作为列表元素list [0] ()         #执行func2   
2. Nesting of functions
def func1 ():    print ("from func1")    def Func2 ():        print ("from Func2")        def func3 ():            print ("from func3") func3 () Func2 () func1 ()     
3. Namespaces and Scopes

Namespaces are places in memory where names and values are bound, such as the corresponding relationship between the address of a variable name and a variable value. This is mainly divided into built-in namespaces, global namespaces, and local namespaces.

The namespaces are loaded in the following order:

    • The Python interpreter loads the built-in namespace when it starts first
    • When executing a PY file, load the global namespace and free up space after the program finishes running
    • If the function is called during execution of the file, the local namespace is generated temporarily, and the space is freed after the function call ends

The lookup order of the first name is the reverse of the load order, the first local namespace, then the global namespace, and the last built-in namespace. Global cannot view local, local can view global.

#优先在func () find Max in the local namespace if there is no global find, if not yet in return Maxmax = 3def func in the built-in namespace :    max = 1    print(max)   Func () 

Global scope: Includes name of built-in name and global namespace, global survival, globally valid, globals ()

Local scope: Name of the local namespace, temporary survival, locally valid, locals ()

xxx=2222yyy= "DSFSF" Print (globals ()) print (Locals ())   #全局作用域中调用locals () is equivalent to calling Globals () def func ():    zzzzz=[1,2,3,4]    print(locals ()) Print (Globals ())   #仅比前面的globals多了func函数名字, Variable name func () defined in the no Func function    

The scope relationship of a function is fixed in the function definition phase, regardless of the location of the call.

xxx = "abc" def Outter ():    def Innner ():        print ("inner", XXX)    return Innnerf =  Outter () def Bar (): x=123456 F () #f () is actually inner (), called when there is no xxx in the local scope, goes to the global scope, cannot call the Xxxbar () in bar (  ) 
4. Closure function

The closure function is a function defined inside the function, the function body code protects the reference to the name of the outer scope (not the global scope), and the outer function usually returns the closure function with return, which can then be used arbitrarily.

Z =1def outter ():    x = 1    y = 2    def inner ():        print(x, y)    return Innerf = outter () print (f.__closure__[0].cell_contents) #返回闭包函数中第一个引用外部名字的值    

The closure function is used primarily as a function of passing values to functions. Because the returned function object wraps a layer of scope, it takes precedence over its own outer scope, regardless of where it is called.

#普通的调用方法, parameters are passed in each execution. Import requestsdef get (URL):    response = requests.get (URL)    if Response.status_code = =:        Print(len (response.text)) Get ("https://www.baidu.com") #使用闭包函数后, parameters are passed in by an external function to facilitate import Requestsdef outter (URL) def get (): Response = requests.get (URL) if Response.status_code = = =: Print(len (r Esponse.text)) return Getbaidu = Outter ("https://www.baidu.com") Baidu ()     
5. Decorative Device

An adorner can be any calling object, and the adorner can be any callable function.

The adorner principle is: The source code of the decorated object is not modified, and the method of calling the decorated object is not modified. (i.e. closed for modification, open for expansion)

The adorner goal is to add new functionality to the adorned object under conditions that satisfy the principle. The interior function is passed through the outer function, and then the decorated function is executed in the inner layer function.

Adorner with no parameters:

Import timedef index ():    time.sleep (3)    print ("Welcome to Index") def Outter (func):    def Inner (): start = time.time () func () stop = time.time () print ("Run time is%s"% (stop-start)) return
            
              Innerindex =
              outter (index) index () 
                    

Cases where the modified function has parameters

Import timedef Index (name):    time.sleep (3)    print ("Welcome%s to index"% name) def  Outter (func):    def inner (*args,**kwargs): start = time.time () func (*args,**kwargs) stop =  Time.time () print ("Run time is%s"% (stop-start)) return Innerindex = outter (index) index ("xxx")
               

There are parametric adorners, the outer layer of the adorner requires only two layers, and the inner layers pass through the parameters of the decorated function. The outer layer is passed in the decorated function name, returning the inner layer function. The outermost incoming inner function requires additional parameters to be introduced, returning the function name of the middle layer.

def auth (driver= ' file '):    def auth2 (func):        def wrapper (*args,**Kwargs):            name = input ("Input User: ")            password = input (" Input password ")            if Driver = =" File ": if name==" xxx "and password==" 123 " c11>: Print ("Login Success") return func (*args,**kwargs) elif Driver = = "LDAP": Print ("LDAP") return wrapper return Auth2@auth (driver= "File") def foo (name): Print ("Welcome" +name) foo ("xxx") 

Adorner syntax

Import timedef outter (func):    def inner (*args,**Kwargs):        start = time.time ()        func (*args, * *Kwargs)        stop = time.time () print ("Run time is%s"% (stop-start)) return inner@outter #相当于index = Outter (index), the adorner function must define DEF index (name) above the modified function: Time.sleep (3) print ("Welcome%s to index"% name) #index = Outter (index) index ("xxx")          

Adorner supplement: Wraps

From functools import wrapsdef Deco (func):    @wraps (func) #将传入被装饰函数的信息赋给内层函数, into the help document, and so on.    def wrapper (*args,**Kwargs): Return        (func (*args,**Kwargs))    return wrapper@decodef index (): "Help document for original index" print ("from index") print (index.__doc__)      

     

Python Learning Note III (file operations, functions)

Related Article

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.