Python exceptions and file reading and writing

Python exception

1. The complete syntax of python exception

the try :
     # prompts the user for an integer 
    NUM = int (INPUT ( " Enter an integer: " ))
     # integer divided by 8 input by the user and outputs 
    Result = 8 / NUM
     Print (Result)
 the except a ValueError:
     Print ( " Enter Correct integer! " )
 Except Exception as result:
     print ( " Unknown error:% s " % result)
 else :
     print ( " Try successful " )
 finally :
     print ( "Code that will be executed regardless of whether there is an error! " )
 print ( " - " * 50)

 2. Python abnormal transitivity

 When an exception occurs in the execution of a function / method, the exception is passed to the calling party of the function / method. If it is passed to the main program, there is still no exception handling before the program is terminated.

# Abnormal transmissibility 
DEF the demo1 ():
     return int (INPUT ( " enter an integer: " )) 


DEF demo2 ():
     return the demo1 ()
 # by transfer of abnormality, abnormality in the main capture 


the try :
     Print (demo2 () )
 except Exception as result:
     print ( " Unknown error:% s " % result)

 3. Python actively throws an exception

def input_password ():
     # 1. Prompt the user to enter the password 
    pwd = input ( " Please enter the password: " )
     # 2. Determine the password length> = 8, return the password entered by the user 
    if len (pwd)> = 8 :
         return pwd
     # 3. If <8 actively throws an exception 
    print ( " actively throws an exception! " )
     # 1> creates an exception object-you can use the error message string as a parameter 
    ex = Exception ( " password length is not enough! " )
     # 2> actively throws abnormal 
    the raise EX 


# prompt the user to enter a password 
the try :
     Print (input_password ())
 the except Exception as result:
    print(result)

 

Python file read and write

1. The file pointer will change after reading the file

# 1. Open the file 
file = open ( " test.py " )
 # 2. Read the file content 
text = file.read ()
 print (text)
 print (len (text))
 print ( " - " * 50 ) 
text = file.read ()
 print (text)
 print (len (text))
 # 3. Close the file 
file.close ()

 2. How to copy small files

# 1. 打开
file_read = open("test.py")
file_write = open("test[复件].py", "w")
# 2. 读、写
text = file_read.read()
file_write.write(text)
# 3. 关闭
file_read.close()
file_write.close()

 3. How to copy large files

# 1. Open 
the file_read = Open ( " the test.py " ) 
file_write = Open ( " Test [copy] .py " , " W " )
 # 2. Read, write 
the while True:
     # to read single line 
    text = file_read.readline ()
     # Determine whether the content is read 
    if  not text:
         break 
    file_write.write (text) 

# 3. Close 
file_read.close () 
file_write.close ()

 

Guess you like

Origin www.cnblogs.com/duxie/p/12681757.html