Python basic 3 file functions,

Source: Internet
Author: User

Python basic 3 file functions,

Today, I will review the previous knowledge about file operations. The operations on files mainly consist of the following parts:

I. Basic file knowledge

1. Basic File Operations

File operations can be divided into three parts:

1. open the file, get the file handle, and assign a variable

2. Read and Write files using a handle

3. close the file after the operation.

The following is a specific example program:

1. after the operation is completed, the with open ('db', 'R') as f: data = f. read () # One-time file content read from the disk to the memory data = f. readline () # Read only one data row at a time data = f, write () # write operations on the file 2. f = open ('db', 'R') f. read () # read the object f. close () # close a file
View Code

2. File opening Mode

File opening format: file handle = open ('file path', 'Mode ')

When opening a file, you need to specify the file path and how to open the file. After opening the file, you can get the file handle and operate on the file later.

File opening modes include:

  • R, read-only mode [default mode. The file must exist. If the file does not exist, an exception is thrown]
  • W, write-only mode [unreadable; created if no data exists; cleared if data exists]
  • X, write-only mode [unreadable; created if no data exists; an error is returned if data exists]
  • A. The append mode is readable. If no content exists, the append mode is created. If yes, only the content is appended]

"+" Indicates that a file can be read and written simultaneously.

  • R +, read/write [readable, writable]
  • W +, write and read [readable, writable]
  • X +, write and read [readable, writable]
  • A +, write and read [readable, writable]

"B" indicates byte operations

  • Rb or r + B
  • Wb or w + B
  • Xb or w + B
  • AB or a + B

Note: When opened in the B mode, the read content is of the byte type. You also need to provide the byte type when writing data. Encoding cannot be specified.

File Operation instance:

Import timewith open ('db', 'R') as f: # line = f. read () # One-time output to memory for calling # line = f. readline () # Only one row can be output to the memory at a time # line = f. readlines () # output to the memory in the form of a list. Each row is an element in the list (line breaks are also output) # line = f. readlines () # output to the memory in the form of a list. Each row is an element in the list (the line break is also output) for line in f: # Use the for loop to output a row, and cancel the line break of each row in the file to operate data = line. strip () time. sleep (1) print (data)
View Code

Common modes of file read/write operations:

With open ('db', 'w') as f: # w mode writes data to f in overwrite mode. write ('dafkhfkk ') with open ('db', 'A') as f: f. write ('I am the total') # Mode a is to write data in the append mode (only to the end of the file) r or rt default mode, in text mode, read the rb binary file w or wt text mode. Before the file storage is opened, the wb binary write is cleared, and the file storage is also cleared by the append mode, only the + read/write mode can be written at the end of the file, and the write mode can only be written at the end of the file w + read/write. The difference with a + is to clear the file content r + read/write, the difference with a + is that it can be written to any location of the file.
View Code

3. open function details:

1. open () syntax

Open (file [, mode [, buffering [, encoding [, errors [, newline [, closefd = True])
Open functions have many parameters, such as file, mode, and encoding.
FileFile Location, which must be enclosed in quotation marks
ModeFile opening mode, see the following 3
BufferingValue Range: 0, 1,> 1. 0 indicates that buffer is disabled (only applicable to binary mode), 1 indicates line buffer (only applicable to text mode),> 1 indicates the initial buffer size;
EncodingIndicates the encoding of the returned data, generally utf8 or gbk;
ErrorsGenerally, strict and ignore are used. When strict is used, an error occurs when the character encoding is incorrect. When ignore is used, the program ignores the Encoding Error, continue to execute the following program.
NewlineThe optional values include None, \ n, \ r, ", '\ r \ n', which is used to differentiate line breaks. However, this parameter is only valid for text mode;
ClosefdThe value is related to the input file parameters. The default value is True. The input file parameter is the file name. When the value is False, the file can only be a file descriptor, what is a file descriptor is a non-negative integer. In a Unix kernel system, a file descriptor is returned when a file is opened.

2. Differences between file () and open () in Python
Both of them can open files and perform operations on files. They also have similar usage and parameters. However, there are essential differences between the two methods,File is a file class., Use file () to open the file, Which is equivalent to constructing a file class, while opening a file with open () isPython built-in functions, We recommend that you use open

4. Summary of the file:

Summary 1 of the file section. Common read/write Methods: r read-only mode; w write-only mode (the content will be overwritten once written each time ); a is written at the end in append mode (does not overwrite the previously written content) 2. readable and writable mode: r + the cursor is at the starting position by default. It writes data in the form of w + overwrite. to read the content, the a + cursor must be adjusted to the last position of the file by default for seek. No matter the cursor position, it must be an append write, to read the content, you must adjust seek in the format of 3.rb wb AB binary.

 

2. Basic knowledge of functions

1. Function Definition in python: a function is a programming method of logical structure and process. My personal understanding of the function is: The function is actually a tool in implementing our main logic and is responsible for implementing specific functions (mainly processing intermediate data, return the final processing result. Return the main logic waiting for calling)

2. Basic Methods for defining functions in Python:

Def func (x1, x2): x = x1 + x2 return xret = func (2, 3) print (ret) def: defines the function's keyword func: function name (): ": Document Description (optional, but it is strongly recommended to add description information for your function) x = x1 + x2: Generic refers to the code block or program processing logic return: run the call to define the return value: either with a parameter or without func () ret receives the return value of the function return. If the function does not return a value, ret receives None.
View Code

Notes:

1. A function in a programming language is a logic encapsulated by a function name to complete a specific function, in programming languages, the same values of parameters passed in by functions may not be the same and other global variable values can be modified (because the execution of function a may depend on the results of another function B, B may get different results. Even if you input the same parameter to a, a will certainly get different results ).

2. Functional Programming: first define a mathematical function (mathematical modeling), and then implement it in a programming language according to this mathematical model.

3. advantages of using function programming:

3. 1. code reuse

. Maintain consistency and ease of maintenance

3. scalability

4. function parameter problems:

Def func (x1, x2): x = x1 + x2 return xret = func (2, 3) print (ret) in this function, x1, x2 is the form parameter, and 2 and 2 are the actual parameters.
View Code
X, y indicates the shape parameter; a, B indicates the memory space allocated by the real parameter, and the allocated memory space is released after the call. # so, the shape parameter is only valid within the function, this variable cannot be used after the function is returned to the main function. #3.2 actual parameters can be constants, variables, expressions, and functions. No matter what the parameter is, they must have a definite value, in order to pass the parameter to the form parameter. While True: a = int (input ('input a: ') B = int (input ('input B:') def tank (x, y ): res = x ** y return res c = tank (a, B) print (c)

5. function value transfer problems:

#1. location parameters (the parameters are one-to-one) def function (x, c, z): y = x + c + z return yres = function (, 4) print (res) #2. Keyword call (no need to specify the corresponding ones) def function (x, c, z ): y = x + c + z return yres = function (c = 2, x = 3, z = 4) print (res) #3. # pass the default parameter (x4 = 5 is used when no value is specified for the actual parameter, and a specified value is used if any value is specified) def func (x1, x2, x4 = 5): x = x1 + x2 + x4 return xret = func (2, 3) print (ret) # 10def func (x1, x2, x4 = 5 ): x = x1 + x2 + x4 return xret = func (4.3, 10) print (ret) #15 #. The use of universal parameters #4.3.1 args returns a tuples, kwargs returns a dictionary Type def function (x, * args, ** kwargs): y = x return y, args, kwargsres = function (1, 2, 3, 4, 5, a = 5, B = 3) print (res) # (1, (2, 3, 4, 5), {'A': 5, 'B': 3 }) #

6. global variables and local scalar

#5.1 if the function does not have the global keyword,
# Read local variables first. If no local variables exist, search for them at the upper level. You can read global variables.
# However, you cannot assign values to global variables. ge: name = 'kjk'
#5.2 if the function contains a global keyword,
# At this time, variables are essentially global variables, which can be read and assigned values.
Name = 'is your 'def func1 (): name = 'A' def func2 (): global name =' B 'print (name) func2 () print (name) print (name) func1 () print (name) # execution result: # You # B # a # B

Understanding that a function is a variable:

Def action (): print 'in the action' logger () action () Error NameError: global name 'logger 'is not defineddef logger (): print 'in the logger' def action (): print 'in the action' logger () action () def action (): print 'in the action' logger () def logger (): print 'in the logger 'action ()

7. recursive call: If a function calls itself internally, this is called a recursive function. If a function is called internally (def contains a function nested like def)

Example of recursive call:

#6.1 instance 1 # def func (n): # print (n) # if int (n/2) = 0: # return # res = func (int (n/2) # return res # a = func (10) # print (a,) the output result is 10521 None.

The implementation steps are as follows:

Recursive features:

1. There must be a clear termination condition

2. Each time you enter a deeper layer of recursion, the problem scale should be reduced compared to the previous recursion.

3. if the recursion efficiency is not high, too many recursive layers will cause stack overflow (in the computer, function calls are implemented through the stack data structure. Every time a function is called, the stack adds a stack frame. Every time the function returns, the stack will subtract a stack frame. Because the stack size is not infinite, too many recursive calls will cause stack overflow)

 

8. Anonymous functions: anonymous functions are specified functions that do not need to be displayed.

Lamdba function: ret = lamdba variable 1, variable 2...: expression returns the result of expression calculation to ret

# This code def calc (n): return n ** nprint (calc (10) # Replace it with the anonymous function calc = lambda n: n ** nprint (calc (10 ))

9. Functional programming:

9.1 High-Order Functions

Any of the two features is a high-order function.

1. The input parameter of the function is a function name.

2. the return value of a function is a function name.

#1. the returned value contains the function name def test1 (): print ('IN the test1') def test (): print ('in the test') return test1res = test () print (res) ret = res () print (ret)

In the test

<Function test1 at 0x02199588>
In the test1
None

#1.2 name = 'Alex 'def foo (): name = 'linhaifeng' def bar (): name = 'wupeiqi' print (name) return barprint (name) a = foo () print (a) B = a () print (B) output result: alex <function foo. <locals>. bar at 0x005E94B0> wupeiqiNone

Map function:

# Function method implementation map function returns each element square in the list to this list '''num _ l = [1, 2, 4, 5, 6] def map_test (array ): ret = [] for I in num_l: ret. append (I ** 2) return retret = map_test (num_l) print (ret) # ultimate version # num_l = [1, 2, 4, 5, 6, 7, 8] # def map_test (func, arry): # func = lambda expression arry = num_l # ret = [] # for I in arry: # res = func (I) # add_one (Implementation) # ret. append (res) # return ret # res = map_test (lambda x: x + 1, num_l) # print (res) # msg = 'linghaifeng' # print (list (map (lambda x: x. upper (), msg )))
The output result is: ['l', 'I', 'n', 'G', 'h', 'A', 'I', 'F ', 'E', 'n', 'G']

Filter Function (Out the content you don't want)

#1. principles # movice_people = ['SB _ qi', 'SB _ rty', 'SB _ kjl ', 'fgd'] # def filter_test (arry ): # ret = [] # for p in arry: # if not p. startswith ('SB '): # ret. append (p) # return ret # print (filter_test (movice_people) # use the self-made filter_test function to determine the function to end with # movice_people1 = ['qwe _ sb ', 'sid _ sb ', 'dfg', 'SB _ dfg'] # def show_sb (n): # return n. endswith ('SB ') # def filter_test (func, arry): # ret = [] # for p in arry: # if not func (p): # ret. append (p) # return ret # res = filter_test (show_sb, movice_people1) # print (res) # filter using the lambda function # def filter_test (func, arry ): # ret = [] # for p in arry: # if not func (p): # ret. append (p) # return ret # res = filter_test (lambda n: n. endswith ('SB '), movice_people1) # print (res) # filter function # ret = filter (lambda n: n. endswith ('SB '), movice_people1) # print (ret) # print (list (ret) # convert ret into a list form # for I in ret: # print (I) output result: <filter object at 0x021046F0> ['qwe _ sb ', 'sid _ sb']

Reduce function: Merge the data and compress the data to produce the final result.

#1. implement the reduce function # num_k = [3,100,] # def performance_test (arry): # res = 0 # for num in arry: # res + = num # return res # print (performance_test (num_k) ### 2. multiply the elements in the list # num_k = [100,] # def multip (x, y): # return x * y # def performance_rest (func, arry ): # res = arry. pop (0) # for num in arry: # res = func (res, num) # return res # print (performance_rest (multip, num_k) # print (performance_rest (lambda x, y: x * y, num_k ))

#3. If the function parameter contains the default parameter (for example, when you perform automatic installation, you can set the optional validation value to the default parameter)
#
# Num_k = [1, 2, 3, 4, 100]
#
# Def performance_rest (func, arry, init = None ):
# If init is None:
# Res = arry. pop (0)
# Else:
# Res = init
# For num in arry:
# Res = func (res, num)
# Return res
# Print (performance_rest (lambda x, y: x * y, num_k), 100)
# Print (performance_rest (lambda x, y: x * y, num_k ),)
#
#4. Use of reduce Functions
# From functools import reduce
# Num_h = [1, 2, 3,100]
# Ret = reduce (lambda x, y: x + y, num_h)
# Print (ret)

 

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.