In Python programming, to implement theThe results of the program are saved to a file, you need to use itFile operationsRelated functions and methods.
The specific operation steps can be divided into the following steps: determine the target file path.
toOpen the file in append mode
Write the data to a file.
Close the file. Among them, when writing data to a file, the specific form is:Write by linewithNot write on a line-by-line basisThere are two kinds of functional functions, and the corresponding functional functions are also different.
The basic Python programming implementation of writing data to a file is as follows:
In the above python **, four functions are used, namely:open, write, writelines, and closeTheir corresponding file operations are:Open a file, write data to a file, and close a file
The open function passes three arguments, from left to rightFile path, file opening mode, file encoding。The file path is, of course, the directory path where the target file is located; The file mode sets specific read and write forms, such as read-only, write-only, overwrite write, append-write, etc.; File encoding is to specify the encoding specifications of the target file, such as UTF-8, GBK, and so on.
Both the write function and the writelines function write data to the target file, the difference is that the latter writes on a line-by-line basis and the former does not write on a line-by-line basis, which is official. However, in my own practice, I have not found such a difference between the two, for example, there is no difference in the execution result of the following paragraph:
As shown in the case of the file content after the program is executed, the write function can also write multiple lines of text data at once.
The close function completes the file closure operation, which is especially important in the actual application development, if there is no such sentence, then other programs that want to use the file may not be able to carry out because the current program is occupied and not released, and once the current program crashes, it may cause file data loss. So, be sure to remember to add a close statement after all file actions