1. Open the file to get the file handle and assign a value to a variable
2. Manipulate the file through a handle
3. Close the file
Sample files
' How are you? ' I'm in the super-uh, bye .
Basic process of file operation
F=open ('Chenli', encoding='Utf-8') First_line=F.readline ()Print('the first line is:', First_line)Print('I'm a split line .'. Center (9,'-'))#9 for string Total 9 lengthData=f.read ()#Read all contentPrint(data)2.2 File Encoding
# do not specify open encoding, which is the Python interpreter default encoding, python2.* is ascii,python3.* for utf-8F=open ('chenli.txt'
F=open ('chenli.txt', encoding='utf-8') F.read ()
2.3 File Open Mode
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 mode, file must exist, not present, throw exception"
- 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"
"+" 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 a byte type, and a byte type is required for writing, and encoding cannot be specified
2.4 File built-in functions flush
Flush principle:
- File operation is the software to read files from the hard disk to memory
- The operation of writing to the file is also stored in buffer buffers (memory speed faster than the hard disk, if the data written to the file from memory to the hard disk, memory and hard disk speed delay will be infinitely amplified, inefficient, so to brush the data to the hard disk we unified into the memory of a small piece of space, buffer, After some time the operating system will flash the data in buffer to the hard disk.
- Flush that is, forcing the written data to be brushed to the hard disk
Scroll bar:
Import Sys,time for inch Range (Ten): sys.stdout.write ('#') Sys.stdout.flush () Time.sleep (0.2)
Python file operations