Python Learning Day3

Source: Internet
Author: User
Tags function definition readline throw exception

One, Python file operation

Basic process of file operation:

The computer system is divided into three parts: the hardware, the operating system and the application.

Applications that we write in Python or other languages need to be saved on the hard drive if we want to keep the data permanently, which involves the application operating hardware, and it is well known that the application is not able to manipulate the hardware directly. The operating system encapsulates complex hardware operations into a simple interface for use by the user/application, where the file is the operating system provided to the application to manipulate the virtual concept of the hard disk, and the user or application can save its own data permanently by manipulating the file.

With the concept of a file, we no longer have to consider the details of the operation of the hard disk, just the process of manipulating the files:

Method One: #打开文件, get the file handle and assign the value to a variable f = open (' D:\code\\1.txt ', encoding= ' utf-8 ', mode= ' R ')  #指定打开文件的自己, by default, open file = F.read in read mode ()  #通过句柄对文件进行操作f.close ()   #关闭文件, use this method to open the file, the operation must be closed, or there will be a memory overflow risk Method II: #次方法的优点不需要担心关闭文件, As long as the code under the WITH statement finishes, the method will automatically help you close the file with open (' D:\code\st.txt ', ' W ') as F:     f.write ("Hello")    #绝对路径 

How to open the file:

#1. The mode of opening the file has (default is text mode):R, read-only mode "default mode, the file must exist, does not exist" throw exception "W, write-only mode" is not readable; "A, append write mode is not readable; Note: The normal work of using R, W, a these three modes are fully sufficient, do not recommend the use of r+, w+ and other modes # #. For non-text files, we can only use B mode, "B" means to operate in bytes (and all files are stored in bytes, The use of this mode does not need to consider the text file character encoding, picture file JGP format, video file avi format)RB Wbab Note: When opened in B, the content read is byte type, write also need to provide byte type, can not specify code # #, ' + ' Mode (is added a function) r+, read and write"readable, can write" w+, write read "writable, readable" A +, write read "writable, readable" #4, to bytes type operation of read-write, write read, write-read mode r+B, read and write "readable, can write" w+B,        Write read "writable, readable" a+b, read "writable, readable"

Common methods of file operation:

F1 = open (' Stewardess nurse teacher housewife. txt ', encoding= ' utf-8 ', mode= ' R ') content =F1.read () Print(content) F1.close () # Read all reads, strongly does not recommend using this method, because the method will load all the files into memory, if the file is too large will burst memory F1 = open (' Log1 ', encoding= ' utf-8 ') content = F1.read () #print (content) F1.close () #read (n) f1 = open (' Log1 ', encoding= ' utf-8 ' ) content = F1.read (5) # R mode is read by character. Print  (content) f1.close () f1 = open (' Log1 ', mode= ' RB ' ) content = F1.read (3) # RB mode reads in bytes. Print (Content.decode (' Utf-8 ' )) F1.close () #readline () read by line f1 = open (' Log1 ', encoding= ' Utf-8 ' ) print  (F1.readline ()) Print  (F1.readline ()) Print  (F1.readline ()) Print  (F1.readline ()) F1.close () # ReadLines () takes each row as an element of the list and returns the list F1 = open (' Log1 ', encoding= ' Utf-8 ' ) print  (F1.readlines ()) F1.close () # For loop F1 = open (' Log1 ', encoding= ' Utf-8 ' ) for I in  f1:print  (i) F1.close () #我们在工作建议使用for循环的方法 # encoding supplement: S1 = B ' \xd6\xd0\xb9\xfa '  s2 = s1.decode (' GBK ' ) s3 = S2.encode (' utf-8 ' ) #将gbk编码转换为utf -8print (S3) # B ' \xe4\ XB8\XAD\XE5\X9B\XBD ' S1 = B ' \xd6\xd0\xb9\xfa '. Decode (' GBK '). Encode (' Utf-8 ' ) print (S1)    

File modification:

1. Open the original file and generate a file handle.
2. Create a new file and generate a file handle.
3, read the original file, make changes, write the new file.
4, delete the original file.
5. Rename the original file with the new file.

#file data is stored on the hard disk, so there is only coverage, there is no modification so to speak, we usually see the modified files, are simulated out of the effect, specifically, there are two ways to achieve:Mode One: The contents of the file stored in the hard disk are loaded into memory, can be modified in memory, and then overwritten by memory to the hard disk (Word,vim,nodpad++and other editors)ImportOs#calling the System moduleWith Open ('a.txt') as Read_f,open ('. A.txt.swap','W') as Write_f:data=read_f.read ()#all read into memory, if the file is large, it will be very cardData=data.replace ('Tom','Jerry')#complete the modifications in memorywrite_f.write (data)#write new files onceOs.remove ('a.txt')#Delete original fileOs.rename ('. A.txt.swap','a.txt')#Rename the newly created file to the original filemethod Two: The contents of the file stored on the hard disk is read into the memory line by line, the modification is completed to write a new file, and finally overwrite the source file with a new fileImportOswith Open ('a.txt') as Read_f,open ('. A.txt.swap','W') as Write_f: forLineinchRead_f:line=line.replace ('Tom','Jerry') Write_f.write (line) Os.remove ('a.txt') Os.rename ('. A.txt.swap','a.txt')

Second, function

Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function .

Functions can improve the modularity of the application, and the reuse of the code. You already know that Python provides many built-in functions, such as print (), Len (), and so on. But you can also create your own functions, which are called user-defined functions.

#function DefinitiondefMylen ():"""calculate the length of a S1"""S1="Hello World"length=0 forIinchS1:length= Length+1Print(length)#function CallMylen ()#function name + () execution function#return value of function" "1, Encounter return, End function. def func1 ():p rint (one) print (Returnprint) (333) print (444) func1 () 2, return a value to the caller (performer) of the function. No return returns Nonereturn not written or None returns Nonereturn returns a single number. Return returns multiple numbers, and multiple numbers are returned in tuples. " "

Function parameters:

#function DefinitiondefMylen (S1):"""calculate the length of a S1"""length=0 forIinchS1:length= Length+1returnlength#function CallStr_len = Mylen ("Hello World")Print('Str_len:%s'%str_len)

We tell the Mylen function to calculate who the string is, this process is called the Pass parameter, referred to as the argument, we call the function when the "Hello World" and the definition of the function S1 is the parameter .

Real participation Formal parameters

The parameters are also different:

The "Hello World" passed when we called the function is called the actual argument, because this is the actual content to be given to the function, referred to as the argument .

The S1 that defines a function is simply the name of a variable, called the formal parameter , because it is only a form when defining a function, which means that there is a parameter, referred to as a formal parameter.

Passing Multiple parameters

Parameters can be passed multiple, and multiple parameters are separated by commas.

def Mymax (x, y    ): if Else y     return  = Mymax (10,20)print(MA)

Dynamic parameter *args,**kwargs Universal parameters

Iii. Namespaces and Scopes

Let's recall how the Python code runs when it encounters a function.

After the Python interpreter starts executing, it opens up a space in memory

Whenever a variable is encountered, the corresponding relationship between the variable name and the value is recorded.

But when a function definition is encountered, the interpreter simply reads the function name into memory , indicating that the function exists, and that the variables inside the function and the logic interpreter do not care at all.

When executing to a function call, the Python interpreter will open up a memory to store the contents of the function , at which point the variables in the function are stored in the newly opened memory. The variables in the function can only be used inside the function, and all the contents of this memory will be emptied as the function executes.

Note: We have a name for the space that "stores the relationship between names and values"-called namespaces

At the beginning of the code, the space created to store the "variable name-value relationship" is called the global namespace , and the temporary space opened in the function's run is called the local namespace .

Namespaces and Scopes:

The namespaces are divided into three types:

Global namespaces

Local namespaces

Built-in namespaces

* The built-in namespace holds the Python interpreter's name for us: Input,print,str,list,tuple ... They are all familiar to us and can be used in a way.

Order of loading and taking values between three namespaces:

Load order: Built-in namespaces (pre-Program load)-Global namespaces (program run: Load from top to bottom) local namespaces (program run: Load only when called)

Value:

Built-in namespaces, local namespaces, and global namespaces, local call spaces

Scope

Scope is the scope of action, according to the effective scope can be divided into global scope and local scope.

Global scope: Contains built-in namespaces, global namespaces , can be referenced anywhere throughout the file, are globally valid

Local scope: Local namespace, only valid locally

Globals and Locals methods

def func ():      A Print ( locals ()) Print (Globals ()) func ()          

Output:

{' B ': +, ' a ': 12}
{' __name__ ': ' __main__ ', ' __doc__ ': None, ' __package__ ': None, ' __loader__ ': <_frozen_importlib_external. Sourcefileloader object at 0x0578a590>, ' __spec__ ': None, ' __annotations__ ': {}, ' __builtins__ ': <module ' builtins ' (built-in), ' __file__ ': ' d:/python/day4/exercise. Py ', ' __cached__ ': None, ' func ': <function func at 0x0582b8e8>}

Closed Package

def func ():     ' Eva '     def inner ():        print (name)

Closure function:

An intrinsic function contains a reference to an outer scope rather than a full-action domain name, which is called a closure function
#函数内部定义的函数称为内部函数

The method of judging closure function __closure__

#输出的__closure__有cell元素: Is the closure function def func ():     ' Eva '     def inner ():        print (name)    print (inner.__closure__)    return=   'Egon'def func2 ():    def inner ():        print (name)    print ( inner.__closure__)    return= func2 () f2 ()

Summarize:

Namespaces:

A total of three namespaces range from large to small in order: built-in namespaces, global namespaces, local namespaces

Scope (including the scope chain of the function):

A small range can be used in a wide range of
But a large range cannot be used in small areas.
range from large to small (figure)

In a small area, if you want to use a variable that is present in this small range, use your own
If not in a small area, use the upper level, the upper level is not used, and so on.
If none, error

Nesting of functions:

Nested calls

Nested definitions: Functions that are defined internally cannot be called directly at the global

The nature of the function name:

is a variable that holds the memory address where the function resides.

Closures:

An intrinsic function contains a reference to an outer scope rather than a full-action domain name, which is called a closure function

Python Learning Day3

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.