Open ()file Open, read, write operations for functions
python file read-write and open operations have their own specific functions and methods. Below we explain the basic use of the open () function in Python, as follows:
1, Pythonopen ()function File Open operation
Opening the file will use the Open function, the standard Python opening file syntax is as follows:
Open (Name[,mode[,buffering]])
Open The file name of the function is required, and both the pattern 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 ')
Here you extend the string about the above statement:
1. Escape character
For example: \ n \ t etc.
2. Raw
This is the example above in X=open (R ' C:\\test\a.txt ') where if you do not use raw
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.
3. Unicode
4. Formatting
For example,%d%f%s
2. Open ()function File open mode parameter common values
' R ' Read mode
' W ' Write mode
' A ' Append mode
' B ' Binary mode
' + ' Read/write mode
3. PythonFile Write operations
>>>f = open (' A.txt ', ' W ')
>>>f.write (' Hello, ')
>>>f.write (' Iplaypython ')
>>>f.close ()
The first line: Open the A.txt file in a written way and assign the variable F
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.
4. Pythonfile 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 the method of reading the file, the parentheses fill in the number of characters to be read, the number of characters filled here is 5, if the fill is 1 then the output should be ' H '.
There are some common techniques for file reading, like the following two types:
1 , read (): reads all content
2 , ReadLine (): Indicates progressive read
This article from "Technology bo" blog, declined reprint!
Python series------Open functions