In the previous chapter, you learned how to use read, readline, and readlines to read a file. If we want to save some data to a file, how do we implement it?
File objects in Python provide a write function that writes specified content to a file. The syntax of the function is as follows:
file.write (string)
Among them, file represents a file object that has been opened; string represents a string (or byte string) that is to be written to a file and is only applicable to a binary file.
Note that when using write function to write data to a file, you must ensure that you use the open function to open the file in r +, w, w +, a, or a + mode, otherwise the execution of the write function will throw an io.UnsupportedOperation error .
For example, create an a.txt file with the following contents:
Python tutorial: www.freelearningpoints.com
Then, create a Python file in the same directory as the a.txt file and write the following code:
f = open("a.txt",'w') f.write("Write more Python tutorials") f.close()
The output is:
27
As mentioned earlier, if w (write) is included in the open file mode, when writing to a file, the contents of the original file will be emptied before new contents are written. So, run the above program and open the a.txt file again, you will only see the newly written content:
If a (append) is included in the open file mode, the original content will not be cleared, but the newly written content will be added after the original content. For example, restore the contents of the a.txt file and modify the above code to:
f = open("a.txt",'w') f.write("\nWrite more Python tutorials") f.close()
The output is:
28
Open a.txt again, you can see the following:
Therefore, using different file opening modes will directly affect the effect of the write function to write data to the file.
In addition, after writing to the file is complete, be sure to call the close function to close the open file, otherwise the written content will not be saved to the file. For example, delete the last line f.close in the above program, run this program again and open a.txt, you will find that the file is empty. This is because when we write the contents of the file, the operating system does not write the data to the disk immediately but caches it first. Only when the close function is called, the operating system guarantees that all the data which not written is written to disk file.
In addition, if you do not want to close the file immediately after writing data to the file, you can also call the flush function provided by the file object, which can write the data in the buffer to the file. Example:
f = open("a.txt",'w') f.write("Write more Python tutorials") f.flush()
The output is:
27
Open the a.txt file and see what's written:
Some readers may think that the buffer can be closed by setting the buffering parameter of the open function, so that the data can be directly written to the file? For files opened in binary format, you do not need to use a buffer, and the written data goes directly to the disk file; but for files opened in text format, you must use a buffer, otherwise the Python interpreter will get a ValueError. Example:
f = open ("a.txt", 'w', buffering = 0) f.write ("Write more Python tutorials")
The output is:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
[ipython-input-21-fa717c88c378] in [module]
----> 1 f = open ("a.txt", 'w', buffering = 0)
ValueError: can't have unbuffered text I/O
In Python's file objects, not only the write function is provided, but also the writelines function, which can write a list of strings to a file.
Note that the only write functions are the write and writelines functions. There is no function named writeline.
For example, using the a.txt file as an example, you can easily copy the data in the a.txt file to other files by using the writelines function. The implementation code is as follows:
f = open('a.txt', 'r') n = open('b.txt','w+') n.writelines(f.readlines()) n.close() f.close()
Execute this code, a b.txt file will be generated in the same directory of the a.txt file, and the data contained in the file is exactly the same as a.txt.
It should be noted that when using the writelines function to write multiple lines of data to a file, newlines are not automatically added to each line. In the above example, the b.txt file displays the data line by line because the readlines function reads the newline character at the end of the line when reading each line.
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises