current position:Home>Python -- file and exception

Python -- file and exception

2022-01-30 16:04:48 un

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Reading data from a file

function open() Take a parameter : The name of the file to open . then Python The specified file will be found in the directory where the currently executed file is located , function open() Returns an object representing a file .

1. Read entire file

with open(" File name ") as file_object:
    contents = file_object.read()
print(contents)
 Copy code 

function open() In parentheses , The input file name is limited to the file stored in the directory of the currently executed file , If the file is not in the current directory , Enter the file path .

2. Read line by line

filename = "name.txt"
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
 Copy code 

rstrip() Used to eliminate redundant blank lines

3. write file

filename = "name.txt"
with open(filename,'w') as file_object:
    file_object.write(" Write content ")
 Copy code 

function open() Provide 7 Basic opening method

File open mode meaning
‘r' read only mode
'w' Overwrite
'x' Create and write
'a' Additional writing
'b' Binary mode
'r' Text file mode
'+' And r,w,x,a Use it together , On the basis of the original function, the read-write function is added at the same time

abnormal

try-except sentence

try:
    < Sentence block 1>
except < exception handling >:
    < Sentence block 2>
……
except < Exception types N>:
    < Sentence block N+1>
except:
    < Sentence block N+2>
 Copy code 

If try The code in the block runs without problems ,python Will skip except Code block ; If try The code in the code block caused the error ,python Will find a match except Code block and run the code in it . such , The user will see a friendly error message , instead of traceback.

Exception statements can also be associated with else and finally Use with reserved words

try:
    < Sentence block 1>
except < Exception types 1>:
    < Sentence block 2>
else:
    < Sentence block 3>
finally:
    < Sentence block 4>,
 Copy code 

copyright notice
author[un],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301604457281.html

Random recommended