We can use the Python writelines method to write a list of lines to a stream. A stream can be text, binary or raw. In this example we will use writelines to write some lines to a text stream. Here is some code:
f = open("file1.txt", "w")
f.writelines(["---Line1---", "---Line2---"])
f.close()
Letβs explain what is happening here:
- The open() method opens a file and returns a corresponding file object f.
- We supply two arguments to the open() method: a filename (file1.txt) in the local path and a mode which is βwβ for write in this case. The mode βwβ opens the file for writing but truncates it first.
- The writelines() method accepts a list of lines (Line1 and Line2). We supply a list of 2 lines in this case. These lines are written to our file object file1.txt. Note that line separators are not added.
- close() flushes and closes the stream. Once the file is closed no further operations are possible. The file can now be found on the local storage of the OS in the same folder as your python script.
When the above code executes there will be a new file on the filesystem. We can read the lines from this new file we just wrote to:
f = open("file1.txt", "r")
print(f.read())
f.close()
#Output
#---Line1------Line2---
Letβs explain what is happening here:
- We use the open() method and we supply the file name (file1.txt) and the mode which is βrβ in this case. The mode βrβ opens the file for reading. The file object f is returned.
- The read() method reads and returns data from the file object until EOF.
- close() flushes and closes the stream.
The output from reading the file may not be as expected. Ideally, we want each line of a different line. Recall that with writelines line separators are not added by default. We have to add our own line separators:
f = open("file1.txt", "w")
f.writelines(["---Line1---\n", "---Line2---\n"])
f.close()
f = open("file1.txt", "r")
print(f.read())
f.close()
#output
#---Line1---
#---Line2---
Note that now we have each line of our list inserted into the file on a different line. All we needed to do was add the new line \n character to each line in the list supplied to the writelines method.
Also, recall that the mode βwβ opens the file for writing but also truncates its contents. By using the mode βaβ in the open() method we can open our file for appending instead.
Mode βaβ opens the file for writing, appending new lines to the end of the file if it exists:
f = open("file1.txt", "a")
f.writelines(["---Line3---\n", "---Line4---\n"])
f.close()
f = open("file1.txt", "r")
print(f.read())
f.close()
#Outputs
#---Line1---
#---Line2---
#---Line3---
#---Line4---
We can actually do the same operation with writelines using a list comprehension:
lines = ['---NewLine---','---NewLine---','---NewLine---']
with open('file2.txt', 'a') as f:
f.writelines(f"{l}\n" for l in lines)
f = open("file2.txt", "r")
print(f.read())
f.close()
#output
#---NewLine---
#---NewLine---
#---NewLine---
Finally, as an alternative to writing a file on disk we can write a text stream to an in-memory text buffer.
import io
output = io.StringIO()
output.writelines(['Line1\n','Line2\n'])
contents = output.getvalue()
print(contents)
output.close()
#output
#Line1
#Line2
Letβs explain what is happening here:
- Import the library io.
- The StringIO() method returns a text buffer output.
- The method writelines allows us to write a list of lines to our in-memory buffer.
- The getvalue() method retrieves the contents of the buffer which we can print.
- The close() method discards the text buffer.
Find the full source code HERE. Thanks for reading. πππ