file.read(1) Read a character
file.seek(0) take file Pointer of only wants position 0, That is, the starting position of the file
file.tell() Displays the current position of the file pointer
file5 = open("name.txt")
fior line in file5.readlines():
print(line)
Means to read the file line by line
file.readline() Means to read a line of file
file.open("name.txt","w') Indicates that the file can be written , The default is r, read-only
file.open("name.txt","a') Indicates that the file can be written , And add new content at the end of the file , If it is w Will overwrite the original content
try:
Abnormal detection
except Exception[,reson]:
except ValueError:
except [ValueError,KeyError]: // Multiple types of exception catches
exception handling
finally:
Whether or not an exception occurs , To perform all
try:
print(1/0)
except ZeroDivisionError as c:
print("0 Not as a divisor %s" %c)
Catch all exceptions
try:
print(1/0)
except Exception as c:
print("0 Not as a divisor %s" %c)
try:
raiseNameError("helloworld)
except NameError:
print("my custom error")
file5 = open("name.txt",encoding="GB18038") Support a Chinese code
The format of the dictionary
dict{" Hash value ":" object ","length":180,"width":80}
dict1={'x':1."y":2}
dict1["z"]=3 // Add a new value to the dictionary
// Read all the values in the dictionary
for each_key in dict1.keys():
print(“%s Value formula of %s”%(each_key,dict1[each_key])) // Output key and value
List derivation
blist=[i*i for i in range(1,11) if(i%2==0)]
Dictionary derivation
z_num={}
fir i in zodiac_name:
z_num[i]=0
After derivation z_num ={i:0 for i in zodiac_name}
22. function
line.strip("\n) Remove line breaks
data.split("|") Use the symbol for the string “|” Separate to get a list
with open("sanguo.txt",encoding="GB18038")as f://with Will be able to open The resulting value is assigned to f
data =f.read().replace("\n","")// Read f The content in , And replace the newline character with null
num=re.find(String,data) // need import re, The said String stay data Is the number of times , If it happens three times , So the return value num And you'll get one list=[String,String,String], If you want to get a number , It can be used len(num)
23. Variable length parameter of function
def func(a,b,c)
print("a= %s" %a)
print("b= %s" %b)
print("c= %s" %c)
func(1,2,3) obtain 1,2,3
func(1,c=3,b=2) a,b,c The result is still 1,2,3, This and java Different , The parameter position can be changed
def howlong(first,*other):// At least one parameter is required , There are as many as you like in the back
print(1+len(other))
howlong(1) // obtain 1
howlong(1,5543,543)// obtain 3
24. The scope of the function
var=123
def func():
global var // Add this sentence , Will affect the external var Value
var=456
print(var)
func()// obtain 456,
print(var)// obtain 123 , Because this variable only becomes... Inside the function 456, If it's in func in Of var Add a keyword before global, So the result is 456, Because of the addition of global It can be regarded as the assignment of global variables
25. Iterators and generators for functions
list=[1,2,3]
it =iter(list)
print(next(it)) // Output one value at a time , An error will be reported more than three times , because list Is the length of the 3
def frange(start,stop,step):
x=start
while x<stop:
yield x // Use yield You can make the function return one value at a time , If there is no such sentence , The call below will report an error
x+=step
for i in frange(10,20,0.5):
print(i)
26 Lambda expression
lambda x: x<=(month,day) Equal to the following function
def function(x)
return x<=(month,day)
lambda x,y:x+y Equal to the following function
def add(x,y)
return x+y
add(3,5)
lambda item:item1 Equal to the following function
def func2(item):
return item[1]
adict={'a':'aa','b':'bb'}
for i in adict.items():
print(func2(i))
31. The use of decorators
def tips(func):
def nei(a,b):
print("start")
func(a,b)
print("end")
return nei
@tips
def add(a,b):
print(a+b)
add(4,5) // The output is start end
print(add(4,5)) // There is one more output session than the above None
def new_tips(argv):
def tips(func):
def nei(a,b):
print("start %s %s" %(argv,func.__name__)) // Can accept external parameters argv, Get the name of the calling function
func(a,b)
print("end")
return nei
return tips
@new_tips("add1") // Parameters in brackets , And method are not the same thing
def add(a,b):
print(a+b)
@new_tips("sub")
def sub(a,b):
print(a-b)
add(4,5)
sub(4,5)
The results are shown below :
start add1 add
9
end
start sub sub
-1
end
32. Custom context manager
fd=open("name.txt")
try:
for line in fd:
print(line)
finally:
fd.close()
The following code has the same function as the above code , When using with When opening a file , If there is an exception in the opening, then with It will be used automatically close Function to close the file
with open ("name.txt") as f:
for line in f:
print(line)
33. Definition of modules
import os // Library function
import time as t// Library function t.time()
import matplotlib as m // Library function , You can simplify the name of the function and use
from time import sleep // In this way, it can be used directly sleep(), No need time As a prefix , But it's not recommended to write , Because in other library functions, there may also be sleep This method , Prevent code confusion
sleep()
import mymode //mymode Modules written by myself , Call the module's... In another file print Method , This print Is custom , It's not systematic print
mymode.print()
34. Grammatical norms
PEP8 Coding standards https://www.python.org/dev/peps/pep-0008/
stay DOS The input pip3 install autopep8
stay pycharm Use the right mouse button inside pep8, The code can be automatically formatted