python: entry to practice learning books (h)

Chapter 10

  File reads:

'' ' 
Open () function takes one argument: the name of the file you want to open. Using an absolute path, can be read anywhere in the file system. For now, the simplest approach is, or will be in the directory where the program files, or a file stored in the directory where the program files folder data file storage. 
Keywords with no need to access the file after it is closed. 
read () method reads the entire contents of this document, and a long string is stored as a variable in the contents. read () is a blank line returns an empty string when reaching the end of the file, but this will be displayed when an empty string. 
'' ' 
With Open ( ' pi_digits.txt ' ) the file_object AS: 
    Contents = file_object.read () 
     Print (contents.rstrip ())
 # read row by row 
with Open ( ' pi_digits.txt ' ) the file_object AS: 
     for Line in the file_object:
             Print (line.rstrip ()) 

# create a file that contains a list of the contents of each line
# The readlines () to read each line from the file, and stores it in a list 
with Open ( ' pi_digits.txt ' ) the file_object AS: 
    Lines = file_object.readlines ()

  When opening a file designated read mode ( 'r'), write mode ( 'w'), additional mode ( 'a') or allow you to read and mode ( 'r +') written to the file. If you omit the mode of argument, Python will default to open the file read-only mode. If you want to write the file does not exist, open () function will automatically create it. However, in order to write ( 'w') mode when opening a file to be careful, because if the specified file already exists, Python clears the file before returning the file object.

  Function write () does not add line breaks at the end of the text you write, let each string on a separate line is required () statement contains newline write.

  Abnormal: Python use a special object called an exception to management errors that occur during program execution. Exceptions are the use of try-except block processing. try-except block let Python perform the specified action, and tell how to do Python exception occurs. When using a try-except block, even if an exception occurs, the program will continue to run: Show friendly error messages you write, rather than make the user confused traceback.

try:
    print(5/0) 
except ZeroDivisionError: 
    print("You can't divide by zero!")

 

Guess you like

Origin www.cnblogs.com/lizhihoublog/p/12583781.html