Python File write() Method – Tutorial with Examples

Python File write() Method

The write() method in Python is a built-in method used to write data to a file. It takes a string argument as input and writes it to the file. If the file does not exist, it will be created. If it already exists, the contents of the file will be overwritten.

Syntax

file.write(string)

Return Value

The write() method returns the number of characters written to the file.

Examples

Example 1: Writing to a file

In this example, we will use the write() method to write data to a file:

file = open("example.txt", "w")
file.write("Hello, world!")
file.close()

In this example, we opened a file “example.txt” in write mode and used the write() method to write the string “Hello, world!” to the file. We then closed the file using the close() method.

Output:

13

The output “13” indicates that 13 characters were written to the file.

Example 2: Appending to a file

In this example, we will use the write() method to append data to a file:

file = open("example.txt", "a")
file.write("\nThis is a new line.")
file.close()

In this example, we opened a file “example.txt” in append mode and used the write() method to append the string “This is a new line.” to the file on a new line. We then closed the file using the close() method.

Output:

21

The output “21” indicates that 21 characters were written to the file.

Example 3: Writing multiple lines to a file

In this example, we will use the write() method to write multiple lines of data to a file:

file = open("example.txt", "w")
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)
file.close()

In this example, we opened a file “example.txt” in write mode and used the writelines() method to write the list of strings “lines” to the file. We then closed the file using the close() method.

Output:

17

The output “17” indicates that 17 characters were written to the file.

Use Cases

The write() method is commonly used in situations where you need to write data to a file, such as logging information or saving user input. It is also useful when you need to overwrite the contents of a file or append data to an existing file.

Conclusion

The write() method is a useful built-in method in Python that allows you to write data to a file. It takes a string argument as input and writes it to the file. If the file does not exist, it will be created. If it already exists, the contents of the file will be overwritten. The write() method returns the number of characters written to the file. It can be used for various use cases such as logging information, saving user input, overwriting file contents, and appending data to an existing file.

Leave a Reply

Your email address will not be published. Required fields are marked *