Python File Write

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.

Example

Python File Write() Method

Let’s understand the code:

  1. The new line is written at the end of the file (not on a new line).
  2. 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.

Example

Python File Write Other Types

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.

Example

Python File Write Line by Line

Tutorials for all brains!