First, open the file
File handle = open (' file path ' mode ')
When you open a file, you need to specify the file path and how you want to open the file, and then open it to get the file handle and manipulate it later through the file handle.
The mode of opening the file is:
- R, read-only mode "default"
- W, write-only mode "unreadable; not exist" created; empty content;
- X, write-only mode "unreadable; not present, create, present error"
- A, append mode "readable; not present, create; append content only;"
# !usr/bin/env python # -*-coding:utf-8-*- f = open ( " history.log , " r ") # data = F.read () # read content and assign to data f.close () Print (data)
# !usr/bin/env python # -*-coding:utf-8-*-f = open ('history1.log','w', encoding='utf-8'# opens the file in write-only mode because the file is not found and is created History1.log data = F.write (' hello ') # reads content and assigns value to dataf.close ()
"+" means you can read and write a file at the same time
- r+, read and write "readable, writable"
- w+, write "readable, writable"
- x+, write "readable, writable"
- A +, write "readable, writable"
"B" means to operate in bytes
- RB or R+b
- WB or W+b
- XB or W+b
- AB or A+b
Note: When opened in B, the content read is byte type, and the byte type is also required for writing
"Python route 19" file operation