Skip to main content

write()

The write() function is used in Python as part of the File Methods. It is used to write data to a file in a specified format. This function takes a string as input and writes it to the file. If the file does not exist, it will be created. If the file already exists, the data will be overwritten with the new content provided in the function call.

Parameter Values

Parameter Description
str

The str parameter is the string of data that will be written to the file.

Return Values

The write() method in Python returns the number of characters written.

How to Use write() in Python

Example 1:

The write() method writes a string to a file. It returns the number of characters written.

with open('file.txt', 'w') as file:
    num_chars = file.write('Hello, World!')
print(num_chars)