Python allows you to write data to a file in multiple ways. You can write one line at a time or write all lines at once. You can also choose to append text to the end of a file instead of writing over it.
To write one line at a time, use the file.write() method. This method takes a string as an input and writes it to the file:
my_file = open("myfile.txt", "w") my_file.write("This is a new line.") my_file.close()
To write multiple lines at once, use the writelines() method. This method takes a list of strings as an input and writes each string on its own line:
my_file = open("myfile.txt", "w") my_list = ["This is line 1\n", "This is line 2\n", "This is line 3\n"] my_file.writelines(my_list) my_file.close()</p><br /><h2>The syntax of the write() method</h2><br /><p>
The write() method takes a string as an argument. This string can contain any number of characters. You can call write() multiple times to insert new lines, or use writelines() if you have a list of strings that you want to insert into the file.
Once you are done writing to the file, you should close it using the close() method, otherwise changes may not be saved to the file.
f = open("output.txt", "w") f.write("this is a test") f.close()
The write() method and files
The write() method writes a specified text to the file.
You can specify the character encoding while opening a file. If you don’t specify the character encoding, the default is platform dependent.
If the specified text is not already in that encoding, write() converts it before writing.
If you open a file in text mode, you can only write string values into it. If you open in binary mode, on the other hand, you can write anything into it, including bytes and bytearray objects.
The return value of the write() method
In Python, the return value of the write() method is the number of characters written to the file.
If you want to write more than one line to a file, you can use the writelines() method. The writelines() method takes a list of strings and writes them to the file in one operation.
For example, if you have a list of strings:
lines = ['Hello, world!', 'python is cool', 'how are you?']
You can write all the strings in one operation:
f = open('myfile.txt', 'w') f.writelines(lines) f.close()
Here are some examples of how to write multiple lines to a file in Python.
With the open() function:
f = open('file.txt', 'w') f.write('Line 1\n') f.write('Line 2\n') f.close()
With the writelines() function:
f = open(‘file.txt’, ‘w’)
lines = [‘Line 1\n’, ‘Line 2\n’] # list of strings to be written to file f.writelines(lines) f.close()
After exploring different ways of writing multiple lines to a file, we learnt that the best way to write multiple lines to a file is by using the writelines() method. This method takes a list of strings as input and writes them to the file. Another advantage of using this method is that it doesn’t add any extra character (like ‘newline’) between the lines.