1. Open/Close file operation
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.
Mode 1: Format: handle= Open ("file name","Mode") MyFile= Open ("1.txt","W")#Open file, this kind of open file mode needs to be closed manuallyMyfile.close ()#Close FileMode 2: Format: with open ("file name","Mode") as handle with open ("1.txt","W") as MyFile:#this way of opening, do not need to manually close the file2. Open mode of File
r: Read-only "read only: Default mode, pointer bit 0" W: Write Only "write only", presence is overwritten, non-existent is created, pointer is 0 "A: Append" Append: Presence is appended, not present created in write, pointer at end "R+ : Read/write: pointer default at Start, Write will overwrite the target location content, can only be written in the open bonnet, or at the end of the write, intermediate write, if from the current position can be written with File1.seek (File1.tell ()) "W+ : Write read" write read: The existence is overwritten, does not exist to create "a + : Write read "write read: There is append, does not exist create in write" RB or R+B "opens a file in binary format for read only. The file pointer will be placed at the beginning of the file. This is the default mode. "WB or W+B" opens a file in binary format for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. "AB or a+B" opens a file in binary format for appending. If the file already exists, the file pointer will put "RB+" to open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. "WB+" opens a file in binary format for reading and writing. Overwrite the file if it already exists. If the file does not exist, create a new file. "AB+" opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write. "Open with no B is a string type with B open with byte (binary) type
3. Common methods
Myfile.seek () # Adjust pointer position myfile.write () # Write content myfile.close () # Close File Myfile.tell () # get pointer current position myfile.read () # Read File contents To read a line from the Myfile.flush () # Refresh Buffer myfile.readline () # myfile.truncate () # intercept content, intercept the current pointer before the content, directly manipulate the original file
4. Read the implementation of each line of a file:
# Method 1 f = open ( " 2.txt ", " r+ " ) line = F.readline () while line: print line line = F.readline () f.close ()
# Method 2 f = open ( " 2.txt ", " r+ " ) ret = F.readlines () for line in RET: print Linef.close ()
# Method 3f = open ("2.txt""r+") for inch f.readlines (): Print linef.close ()
Python file read and write operations