Python learns a third pit

Source: Internet
Author: User

######################### #python Chapter III ################################
This chapter is mainly about the operation of files, as well as part of the functions involved.

PS: Finishing Blog is a bother, this is my notes, originally online pretty good. It's like a bear to get here, no way. Live and watch.


File operation:


File operations are generally open, or files,
The format is as follows:
Variable name = open (' File path ', ' pattern ', ' character encoding ')

Read the file needs to operate the hardware, the user is unable to directly manipulate the hardware, the general operating system has this function to call the hardware, so when you tell you
Operating system to read a.txt this file, the operating system will return the identity of a file, which is the file handle, you only
Get the handle of this file before you can go to the operation. Be sure to close it after the operation is complete, do not always occupy the manger not to poop. Someone else has to use it.
it.

File operations from a large direction, there is nothing more than two: Read and write. And then the two of them began to diverge.
1. Read
Read according to the requirements and points:
Read Only: R can only be read and cannot be written
Reading and writing: r+ can be read or written, but
Binary read: RB (R+B) This is the binary format of the photo read. (such as reading non-text, you must use B)

# # # # #注意 #######

1. If a file does not exist, the error will be read

###### ####################################
Read some of the actions:
f = open (' A.txt ', ' R ', encoding= ' utf-8 ') #获取文件句柄
data = F.read ()
F.close () #关闭文件
Print (data) #大打印文件内容

Several ways to read a file:
Read (): reads all the contents of the file into memory, if the file is too large, do not do so.
ReadLines (): reads all the contents of a file into memory, returns a list
ReadLine (): reads a file, but does not read it all, but reads a row of rows. Chestnuts are as follows:
f = open (' A.txt ', ' R ', encoding= ' utf-8 ')
F.seek (0)
data = F.readline ()
While data:
Print (Data.strip ())
data = F.readline (). Strip ()
F.close ()
Readable (): Checks if the file is readable and returns a bool value.

# #这个是读取一个图片的例子
Import OS
With open (' sb.jpg ', ' RB ') as Read_f,open (' new_sb.jpg ', ' WB ') as Write_f:
Write_f.write (Read_f.read ())
Os.remove (' sb.jpg ')
Os.rename (' new_sb.jpg ', ' sb.jpg ')

To close the parameters of a file:
Close (): Close file
Closed (): Whether the file is closed

2. Write
Write according to the needs and points:
Write only: W can only write, cannot read
Write read: w+ can write, also can read
Binary write: WB (W+B) This is written in binary format. (such as writing non-text, you have to use B)


########### Note #########

1. When using write, the file is emptied, and then written, the original file content does not exist
2. If the file does not exist, create

####################################


How to write:
Write (): Write content
Writelines (): What is written is an object that can be iterated, and he will iterate over it one after the other. Then write the file
Writeable (): Detects if writable


Here comes a new write------append
Append: A This is only appended,
Read and write: A + This can be written, can read
Binary append: AB (a+b) This is the binary format of the photo appended. (such as writing non-text, you have to use B)

Additional methods of operation:
and write the operation method, the same, but at the end of the content added

Other ways to manipulate files:
Seek (): The cursor is anywhere in the content, but in bytes. There are three numbers 0 1 2
0---> The beginning of the article
1---> Position of the current cursor
2---> End of article

Seek (p,0) moves when the file is at p Byte, absolute position
Seek (p,1) moves to p bytes relative to the current position
Seek (p,2) moves to p bytes after the end of the article

Truncate (): truncation, also according to the byte, only keep the front, the back of Do not
Flush (): Flush to disk


Another method of manipulating a file is called context Management, and if so, there is no need to write the close () method.
With open (' A.txt ', ' R ', encoding= ' Utf-8 ') as F1,open (' b.txt ', ' w+ ', encoding= ' Utf-8 ') as F2:
Print (F1.readlines ())
Print (F2.readlines ())

A simple tail-f function
Import time
With open (' Access.log ', ' R ', encoding= ' Utf-8 ') as Read_f:
Read_f.seek (0,2)
While True:
data = Read_f.read (). Strip ()
If data:
Print (' Add a row of data: ', data)
Time.sleep (0.5)

########################## function ################################

Reason for function use:
1. Convenient management
2. Reduced code redundancy,
3. Structural, high readability


There are two types of Python functions: One is a built-in function and one is a custom function
Built-in functions:
The most common way to do this is by the function of a string.
For example, Max min Reserve sort in list, etc.
Custom functions:
As the name implies, the function you define, as to why it is defined, is not a function in the system that satisfies its own needs.
Format:
def function name ():
function body
......

Parameters of the function:
From a large point of view, there are two types of arguments and formal parameters, in which the parameters are created when the function is called.

# # #定义阶段
def print_new (x, Y, z): # #这里的x, y is the formal parameter, the function of the formal parameter, and must be transmitted at the time of the call.
Print (y) # # Pass the value must correspond
Print (y)
Print (z)

# # #调用阶段
Print_new (Three-way) # #这里的1和2就是实参, there are two ways to pass the value, if it is explicitly specified, you can not
Print_new (y=2,x=2222,z=666) # #理会参数的顺序


There are several parameters to continue the subdivision:
Positional parameters, keyword parameters, default parameters, variable length parameters (*args,**kwargs), named keyword parameters


Positional parameters: Not explained, the above example is the position parameter

Keyword parameter: key=value This is the case when the function is called, print_new (y=2,x=1111), which is
It's called the keyword parameter.
# # # #注意事项 # #
1: The keyword argument must be behind the location argument
Print_new (1,y=222,z=6666)
2: Cannot repeat the value of a shape parameter
Print_new (2,x=2,z=666,y=222) # # #这个是错误的

Default parameters: This is what happens because it reduces the duplication of operations.
Example:
def new_foo (name,sex,age=18):
The gender of A= ' {} is {}, his age is {} '
Print (A.format (name,sex,age))
New_foo (' Liu Kang ', ' male
If the user does not enter age, the value inside the function is automatically used, and if the user enters a value, the value that the user enters

# # # # #注意事项 #####
1. When defining default parameters, be sure to write them after the position parameter,
2. The default parameter is defined only once in the definition phase and only once (that is,
Even if you declare a variable outside, you can't change the result)
Age=20
def new_foo (name,sex,age=18):
The gender of A= ' {} is {}, his age is {} '
Print (A.format (name,sex,age))
Age = 16
New_foo (' Liu Kang ', ' Man ') # #age的结果仍是18
3. The value of the default parameter is usually defined as an immutable type


Variable length parameter: This parameter is divided into two kinds, one is *args and the other is **kwargs

1. *args:
* The overflow is received by the location-defined argument, and is assigned to args in the form of a tuple
def test_foo (X,y,*args):
Print (x, y)
Print (args) # # #这个地方打印的其实是元组
Test_foo (111,222,333,444,555)
>>> 111 222
(333,444,555)


2. **kwarges: This will accept the default parameters of the overflow, in the form of a dictionary to Kwargs
def test_foo2 (X,y,**kwargs):
Print (x, y)
Print (Kwargs) # # #这个地方打印的其实是个字典
Test_foo2 (' Liu ', ' Kang ', name= ' Liukang ', age=18)

def foo (Name,age,**kwargs):
Print (Name,age)
If ' sex ' in Kwargs:
Print (kwargs[' sex ')
If ' height ' in Kwargs:
Print (kwargs[' height ')

Foo (' Liukagn ', 18,sex= ' man ', height=188)

Named keyword parameter: A very wonderful one, separated by the "*" number

def foo_name (name,age,*,sex= ' male ', height):
Print (Name,age)
Print (Sex,height)
Foo_name (' Liukang ', 18,height=188)
# The argument after the * is called the named keyword parameter, which must be passed to the value, and must be a keyword
# The way to pass the value of the argument


A small example of the relationship between *args and **kwargs, in addition, if *args and **kwargs are used, all parameters can be accepted.
def foo (x, Y, z):
Print (' from foo: ', x, Y, z)
def foo2 (*args,**kwargs):
Print (args) # (1,)
Print (Kwargs) #{' Z ': 2, ' Y ': 3}
Foo (*args,**kwargs) #foo (* (1,), z=2,y=3)
Foo2 (1,z=2,y=3)
# #上面的效果和下面的一样
Foo (* (1,), z=2,y=3)

Python learns a third pit

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.