Python File Write - write() method
The write() method is used to write into a file using the file object. This is an inbuilt method of Python.
write() method writes strings into the file. Always remember to close the file object after using it.
Syntax: write(string)
- ‘string‘ parameter is the string that you want to write into your file.
- write() method returns the number of characters written by it.
Note When the open() function is called in the 'w' write mode, it automatically creates a new file with the specified name.
Example
Let’s understand the code:
- The new line is written at the end of the file (not on a new line).
- The write() method returns the number of characters written by the method.
Python File Write - write other string types
In Python, you are not limited to writing only strings in a file with write() method. Almost every object type can be converted to a string type. Therefore you can write pretty much everything into a file, for example: a list, a tuple, etc.
Note Creating a new 'example.txt' file will overwrite the previous one.
Example
Python Write file line by line
Writing into a file normally adds the string at the end of the last line of the file. If you want to add the string in a new line, you will have to add the new line character ‘\n‘ at the end of each string.