Python Learning Path (vi)

Source: Internet
Author: User

Today to introduce the operation of the file, including file additions and deletions, as well as character encoding and transcoding, there are some simple function operation.

To operate the file, open a file first, and open the file need to declare what to do with the file, such as read (' R '), write (' W '), append (' a '), read and write (' r+ '), write read (' w+ '), also need to tell the system, what character set to open, such as Utf-8 or Unicode, etc.
Let's start by describing the file read. F.read This is the content that reads the entire file.

First there is a text file called ' Yesterday' (as he has, I did not write this file here) F=open ('yesterday','r', encoding= 'utf-8')
Data1=f.read
Data2=f.read
Print (Data1, "1")
Print (Data2, "2")
F.close

You will find that the output is data1 output is the contents of the file, data2 output is empty, instead of outputting two times the entire file, nor read two lines. Because here, to introduce a handle to something, you can understand the cursor, F.read read the file, the handle is stuck in the last position of the file,

In the execution of the data2, the handle is in the last position, and there is no content in the back, so the output is an empty one. Instead of reading the file twice.

It is also important to note that the file regardless of the operation, as long as the file opened, it must be closed, f.close.

Sometimes we may not need to read the entire file directly, here is a look at the line read F.readline

Here are a few ways
F=open (' Yesterday ', ' R ', encoding= ' utf-8 ')
We can read a few lines from the first line.
For I in range (5):
Print (F.readline ())
You can also read the entire file.
For line in F.readlines ():
Print (Line.strip ())

Here's another operation that is output by line and writes out which is the number of lines used by enumerate
For Index,line in Enumerate (F.readlines ()):
Print (Index,line)

However, the ReadLine command is fully read into memory and runs faster than reading a line in memory, and deleting a line is faster
For line in F:
Print (line)

The file read is introduced almost, the following describes the file write, ' W ' mode is write mode, he is created (if the file exists on the overwrite) a file.

F=open ('yesterday','w', encoding='utf-8')
F.write ("abc")
F.weite ("456")
F.close

After the code executes, I see a row of data in the yesterday file abc456, which he did not write to our program in two lines, but also because the handle mentioned above, because after writing ABC, the handle stays behind the ABC, there is no word wrap, so when writing 456, He will write immediately after ABC.

There is also a point, that is, in the writing process of the file, not after the write code is completed, it is immediately written to the hard disk file, but when the file is closed, the data will be written to disk, before it is stored in memory, so it is also necessary to remember to close the file.

If you want to write immediately after writing, you can use the Write statement after the F.flush () this is written directly to the file, do not need to close the file, in parentheses if the number is written so many characters after writing the file automatically.

There are several open modes of files

A. "A" In this mode, the data written will be appended to the end of the original file without overwriting the original file.

B. "R+" This is a read-write mode, the so-called read and write mode is the first read and write mode. When you read three lines and then write, the newly written file appears at the end of the third line instead of the fourth line. Because the handle of the file stays at the end of the third line at the end of the read, and the handle is not automatically moved to line fourth, the newly written data appears at the end of the third line. Read-write mode, readable and writable can be added, usually more useful.

C. "W+" This is the write-read mode, in this mode, the system will automatically go to find there is no this file, if not, directly create a new file, if any, overwrite this file. In read/write mode, it is useless to read the file first, because the file is overwritten and no data is read. While writing, the handle can be moved, but it cannot be written at the moved handle, or it will be written at the end of the file.

D. "A +" is an additional read/write

E. "RB" allows the file to be read in binary mode.

F. "WB" is written in binary mode. At this time can not input English, Chinese characters and so on, when writing will error, because the input is not binary.

Here is a description of the file changes. There are two ways to modify a file.

1. Read all the files into memory, and then write them all after the modification is complete. This method is not recommended, because when the file is too large, memory may not be able to process the file, and even if it is a generic file, processing speed is slower, because the memory is relatively large.

2. Open the original file at the same time open another file, the modification of the completed file to another new file, so that can be part of the execution, improve running speed, save memory, is the main way to modify the file.

The modified statement can be used with replace

in F:    "ABC in line:line = Line.repiace ("ABC","def") This implements a feature that replaces ABC in the file with def. 

Open the file there is another operation, that is, with the advantage of using with is not to close the file, he will automatically help you handle

With open ("Yesterday","R", encoding="Utf-8") as F: print (F.readline () The way to open multiple files is with open (yesterday1  ", " r ", Encoding=" utf-8) as F, with open ( "yesterday2" r " utf-8 ") as FF: The next file is to be indented.  

The following describes the character encoding and transcoding
The default encoding in Python3 is Unicode. In the Py3 encode, the transcoding will also change the string to bytes type, decode decoding will also turn bytes back to string.

Whether it's encode or decode. Just remember to go through Unicode and move to another character set when different character sets are converted!!!

Utf-8 is an extended set of Unicode, so Unicode can be printed directly under Utf-8.

Finally, a subset of functions are introduced.

So, first define a function

def Test (x):   x+=1   return 0 

Thus, we define a function named Test, whose formal parameter is X, whose function body is x+=1, and the return value is a 0. If return is not specified in the function, the return value of this function is None
The biggest difference between a function and a procedure is that the function must have a return value, and the procedure has no return value.

Return can be followed by anything, he represents a function execution completion of a flag, the return of this value is equivalent to saying that the function has been completed, and in the function, the statement after return is not executed, because return is the end of the function.

Suppose a a= test (1) prints he will get 0. This is the last sign of the function execution. You can also return x. This will print out a 2. Because there are x+=1 in the function. x becomes 2 when execution is complete.

Formal parameters and arguments:

Parameter: The variable allocates the memory unit only when it is called, and immediately releases the allocated memory unit at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

Arguments: Can be constants, variables, expressions, functions, and so on, regardless of the amount of the actual argument, they must have a definite value when making a function call to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

Just like the example above, X is a formal parameter. And the 1 in A=test (1) is the argument.

A function can have multiple parameters and arguments, such as the following code

def Test (x, y    ): Print (x)     Print (y)     return 0test ()Test (x=1,y=2) test (1,y=2) above three kinds of call functions of the method of the parameters of the first two do not have to say, the third method, in the function, He will take the initiative to identify the positional parameters and then go to see assignments. However, the assignment cannot be unloaded before the position parameter is

Function can also assign default parameters

def Test (X,y=1)    print(x)    print(y)    return  0test (1) test(1,3) test(1,y=3) test (x=1) test (x=1,y=3 The above methods are correct, and the default parameters can be assigned or not assigned. This is used for cases with default options, such as default nationality, or default database server port, etc.

Functions can also be transmitted by means of meta-ancestors, dictionaries, etc.

def Test (*args)     print(args)     return  0test (1,2,3,4 Test (*[1,2,3,4]) These two can also be used for this method of transmission is more useful with the flyer a parameter to pass the case, such as the beginning I defined a function, only a parameter x, but later found that the formal parameters are not enough, but also want to add, you can use the following method, Save the future, then change the code def Test (x,*args    )print  (x     )print (args)      return 0 You can use Test (1,2,3,41(2,3,4)

Passing values through a dictionary

defStu_register (Name,age,*args,**kwargs):#*kwargs will turn multiple incoming parameters into a dict form.    Print(Name,age,args,kwargs)
return 0 Stu_register (
"Alex", 22) #Output#Alex () {} #后面这个 {} is Kwargs, just because no value is passed, so it is emptyStu_register ("Jack", 32,"CN","Python", sex="Male", province="Shandong") #Output#Jack (' CN ', ' Python ') {' Province ': ' Shandong ', ' sex ': ' Male '}

Since it falls to the function, local variables and global variables must be unavoidable.

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable. The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable. When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables; global variables work elsewhere
X=1def aaa (x, y)    print(×)    x=3    print(x) c=x+return 0aaa (x,1) print (x)         
After this function is executed is 131 at the top of the program is the global variable and the x inside the function is a local variable although it is possible to change global variables through statement global in a function, it is not recommended. Moreover, only str, int can no longer change local variables in the function. However, lists, meta-ancestors, dictionaries, collections, and classes can all change global variables in local variables. Recursive functions

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

def Calc (n):      Print (n)      if int (N/2) = =0         :return  n     return calc (int (N/2))   Calc (+)   

Recursive properties:

1. There must be a clear end condition

2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion

3. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

Higher order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

Note: ABS is to take absolute value

def Add (x,y,f):      return f (x) + f (y)     = Add (3,-6Print

Python Learning Path (vi)

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.