To write to a text file in Python, you have to use the open() and write() functions. The open() function takes two parameters: file name and file access mode. The returned value of open() is the file object.
The file object is a mediator that can be used by the write() function to pass value to a file.
with open('D:/text_file.txt', 'w') as f: f.write('Just a simple text.')
If the file doesn’t exist, it’s created. If it’s already present, it’s overwritten.
Locate and open the file to see that the file is present and the text is written to a file.
Writing to a file without “with”
When you use the “with” statement, the object is automatically closed if it leaves the scope.
with open('D:/text_file.txt', 'w') as f: f.write('Just a simple text.') print(f.closed) print(f.closed)
The first print function returns False because we are still within the “with” scope therefore the file is not closed. When we leave the scope the function returns True.
You can also create code that writes to a file without using “with”.
f = open('D:/text_file.txt', 'w') f.write('Just a simple text without "with".') print(f.closed) f.close() print(f.closed)
This code creates and opens a file. Next, it writes the string to the file with the write() function. It doesn’t close the file object at the end – you have to do it explicitly. To prove it, there are two print functions. If you run the code the function will return these values:
The first value returns False because the file object is not closed, the second value is True because the close method is executed just before the second print.
Adding the newline character
So far we’ve used only one write() function. Let’s add the second function with additional text.
with open('D:/text_file.txt', 'w') as f: f.write('First text.') f.write('Second text.')
The is no newline (\n) character inside the text, therefore the second text is written just after the first one.
First text.Second text.
If you want to write one text after another, you have to add this character at the end of the first line.
with open('D:/text_file.txt', 'w') as f: f.write('First text.\n') f.write('Second text.\n')
The newline character is added just after the first string, moving the cursor to the new line. The second string is written and new lines are added just after that. It’s not necessary in this case, as there is no additional text after that, but it places the cursor in a new line, so the next string will be placed correctly.
First text. Second text.
Write vs writeline
The write() function takes a string as a parameter. The writeline() function can also take a single string, but you can additionally put there a list of strings.
my_list = ['First text.\n', 'Second text.\n'] with open('D:/text_file.txt', 'w') as f: f.writelines(my_list)
This code will give us the same result as the previous one.
First text. Second text.
If you want to pass a list of strings to write(), you can do it using the for loop and write them line by line.
my_list = ['First text.\n', 'Second text.\n'] with open('D:/text_file.txt', 'w') as f: for line in my_list: f.writelines(line)
Another, more compact way to do it, is to use the join() function. This function merges all strings from the list using the separator.
my_list = ['First text.\n', 'Second text.\n'] with open('D:/text_file.txt', 'w') as f: f.write(''.join(my_list))
In this case, we shouldn’t use the new line separator with the join() function, because there are newline characters at the end of each list element.
If we have a lot of strings inside a list, a better way would be to add the separator not within the list elements, but with the join() function.
my_list = ['First text.', 'Second text.'] with open('D:/text_file.txt', 'w') as f: f.write('\n'.join(my_list))
Append to a text file
When it comes to accessing the file, there are six access modes. We are going to use only two as the other ones are used for reading files. We have used the ‘w’ access file for writing, not we will take a closer look at the append ‘a’ access mode.
|Write only (w)||Open file for writing. The handle is positioned at the beginning of the file. Creates a new file if the file doesn’t exist. For an existing file, the data is overwritten.|
|Append only (a)||Open file for writing. The handle is positioned at the end of the file. The file is created if it doesn’t exist.|
The only modification we have to do, to open the file in append mode, is to change the letter ‘w’ to ‘a’.
Delete the file and run the code again.
with open('D:/text_file.txt', 'a') as f: f.write('First text.\n') f.writelines('Second text.\n')
If you run the code for the first time, it’s going to return the same result as before. But if you run it for the second time, it will move the cursor to the end of the file and write two lines there.
First text. Second text. First text. Second text.