Python Tutorial - Write and Writelines Function

Python Exercise Lists

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:

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")

The output is:


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")

The output is:


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")

The output is:


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

Python Writelines Function

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+')

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)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises