Python study notes 9-file read/write,
1. Read files:
F = open ('directory', 'read/Write mode', encoding = 'gbk, error = 'egiong '). The last three items can be left blank, but the default value is 'R; the read () method is automatically added to the file object opened by the open function;
F. read () read the file you just opened. Remember to close () the function at last; otherwise, unpredictable consequences may occur.
Read/write mode: r read-only, r + read/write, w new (will overwrite the original file), a append, B binary file. Common Mode. For example, 'rb', 'wb ', 'r + B', etc.
The readline () function reads multiple files in turn and returns the list by row. An iteration is used for reading,Print (line. strip ()#Remove/n from each line
With open('nihaoa.txt ') as f: facilitates the way to throw exceptions in try finally.
For I in f. readlines ():
Print (I. strip ())
2. Write files:
Open the file first, and then use the write method. To prevent the use of
With open('nihaoa.txt ', 'w') as f:
F. write ('woshidahaoren ')
Note that the write method will directly overwrite the original file content;