Python learning note 5:python Read and write files
First, the open mode of the file
1. Open File
1) f=open (' D:\\a.txt ', ' W ')
The first parameter is the path to the file, and if only the name of the file is written, the default is the file under the current execution directory, and the second parameter is the open mode of the file.
This way to open the file, after the use of it must remember, close the file: F.close ()
2) with open (' D:\\a.txt ', ' W ') as F
This way the file is opened and the file is automatically closed after it is used, no close is required
2. Open mode of File
In general, there are three types of open files: Read, write, append
This is derived from the following:
Ii. methods of reading and writing files
III. Traversal of files
Looping is the contents of each line of the file
Iv. Modifying the contents of a file-using 2 files
Scene:
There is a file with content written inside it, now modify the contents of the file, and then save it.
Ideas:
Open the file, use the loop method, read a line, modify/not modify the contents of this line, and then write the new file inside; Finally, delete the old file and name the new file the same as the original name.
Scenario Instantiation: D disk has a file a.txt, its content is like, now the file of all 12 changed to 00
Code implementation: (After the modification, D disk only one file a.txt, content such as two)
Python learning note 5:python Read and write files