One, the Python open () function file opening operation
Opening the file will use the Open function, the standard Python opening file syntax is as follows:
Open (Name[,mode[,buffering]])
The file name of the Open function is required, and both the schema and the buffer parameters are optional. For example, there is a a.txt text file, stored in the C:\text, then you want to open it can be done:
>>>x = open (R ' C:\text\a.txt ')
Use the read mode to open the corresponding text file under this path, if you want to open the image does not exist, the program will error.
Ii. What are the common values of open () function file opening mode parameters?
Just opened the file process to use the ' r ' parameter, in the file opening process will also use a lot of methods, have different parameters to represent. ' R ' read mode, ' W ' write mode, ' a ' append mode, ' B ' binary mode, ' + ' read/write mode.
Third, Python file write operation
>>>f = open (' A.txt ', ' W ')
>>>f.write (' Hello, ')
>>>f.write (' Iplaypython ')
>>>f.close ()
The first line: Open the A.txt file in writing and assign it to f (Python variable naming convention)
Second line: The F.write Method writes () the contents in parentheses
The third line: The meaning of the second line is the same, the emphasis is to explain that the content written by F.write will append to the existing data in the file, that is, the ' Iplaypython ' is displayed behind ' Hello, '.
Line four: The last call to close method closes the file, there will be a close.
Iv. Python file read operation method
In order to read the file operation, only need to change the mode to ' r ' can, or the mode is empty do not write parameters, but also the meaning of reading, because the program by default is ' R '.
>>>f = open (' A.txt ', ' R ')
>>>f.read (5)
' Hello '
Read () is a method of reading a file, the number of characters to be read in parentheses, the number of characters filled in here is 5, if the fill is 1 then the output should be ' H '.
Open file file Reading There are also some common techniques, like the following two types:
1. Read (): reads all content
2, ReadLine (): Read line by row
The Python open () function file opens, reads, and writes the underlying operation first.
Python open () function file opening, reading, and writing detailed instructions