A Quick Answer
In Python, one can write a new line into a file using either of the following methods:
- Using built-in open() function
1 2 3 |
f = open('readme.txt', 'a') f.write("this is the start.\n") f.close() |
- Using the open() function with the “with” statement
1 2 |
with open('readme.txt', 'a') as f: f.write("this is the start.\n") |
Either of the above methods will append the line “this is the start.” into the last line in the “readme.txt” file. In this case, we assume that the executed Python script is in the same directory as the text file. That should not be a big problem anyway because if the file does not exist, it is created but it’s essential to take note.
Writing New Line into File in Python
Python has a built-in function called open() that can be used to read and/or modify files. The function returns a file object (also called a handle) that allows us to work with open files. The general syntax for the function is:
<open(file_path, mode=’r’, encoding=None)>
Where file_path is the path to the file to be opened (it can be a full path or a path relative to the current working directory), the mode is the permissions we have when accessing the file. Here are some main access modes available:
Mode | Description |
r | Opens the file in a read-only mode access level. It throws an error if the file does not exist. It is the default mode. |
w | Open for writing, truncating the file first, that is, it overrides the file if it exists. If the file does not exist, it is created. |
a | Open the file for appending to the end of the file. In the latest Python, it’s created if the file does not exist. If that does not happen, you can use “a+” mode. |
x | Open the file for first-time creation. It fails if the file already exists. |
+ | Opens the file for updating. They are used with the other modes above. |
To write a new line to a file in Python, we will use “a” access mode to append the line into the file. There are two ways to do this.
Method 1: Using open() built-in function
For example,
1 2 3 4 5 6 |
f = open('readme.txt', 'a') for i in range(3): f.write(f"Line # {i}\n") f.close() |
Output (left: running the code once, right: executing the code twice) :
In the code snippet, we open the readme.txt file, write 3 lines through a for-loop, and explicitly close the file. Closing the file ensures that the memory used to keep the file open is released. Every time the code is executed, the 3 lines are appended to the file, as shown in the Figure above (right), where the code is executed twice. Note also, that we used the next line character, “\n”, to ensure that each text is written in a new line.
Method 2: Using open() function with with statement
The following code can be used to accomplish the work shown in method 1.
1 2 3 4 |
with open("readme.txt", "a") as f: for i in range(3): f.write(f"Line # {i}\n") |
As you can see, a statement does not require us to close the file handler explicitly. It closes once the code inside the statement is executed, even if there is an error in the code.
This is a preferable method to use not only because it allows us to write clean code but also simplifies the management of memory and computation resources like file streams.
Writing Several Lines into a file
Now that we already know how to write a new line into a file in Python, in this section, we will extend that knowledge to writing multiple lines of strings into a file.
1 2 3 4 5 6 7 8 9 10 11 12 |
# list of elements we want to write data = [253, "Smith", "John", None] # convert each element into string data = list(map(str, data)) # join with "\n" to allow us to move into a new line for each element write_data = "\n".join(data) # write into readme1.txt with open('readme1.txt', 'a') as f: f.write(write_data+"\n") |
Output:
The write() function accepts string data types only and therefore can’t write our data directly because we have an integer and None. We used the map() function to convert the items into strings and added the newline character “\n” so that each item is written to a new line.
map(func, iterable) applies the function func to each item of a given iterable (list, tuple, etc.). It returns a map object (an iterator) of the results we can cast into a list.