In Python, there are four types of basic operations for a file:
1. Open File
File_obj = open ("File path", "mode") the commonly used opening file modes are:
R: Open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
W: Open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.
A: Open a file for append. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.
w+: Opens a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
2. Read the contents of the file
Obj.read (): Load all content into memory at once
Obj.readlines (): Loads all content into memory at once and splits it into strings based on rows
For line in obj:
Print Line
-------------Read only one row of data at a time
3. Write the contents of the file
Obj.write (' content '): Write content to a file
4. Close the file handle
Obj.close (): Close file
Common usage:
Read
1 obj = open ("test.log","R")2 for in obj:3 print(line)4 Obj.close ()
Write
1 obj = open ("test.log","w")2 Obj.write ("This is the firstline\n")3 obj.write ( "This is thesecond line\n")4 obj.close ()
Additional
1 obj = open ("test.log","a")2 Obj.write ("This is thethree line\n")3 obj.close ()
Write read
1 obj = open ("test.log","w+")2 Obj.write ("new line\n")3 print(" data:", Obj.read ())4 obj.close ()
Attention:
1. Cannot write when reading, cannot read when writing
2. The contents of the original file will be flushed out every time you use the read-write.
3. When using the file, always remember to close it when you open it
Basic operations for Python files