Write

Python File Write Operations

Python provides built-in functions to perform file operations like reading, writing, and appending data to the file. In this section, we will focus on the write operation in Python.

To write data into a file, Python provides the write() function. This function is used to write a specified text or string into the file.

1# opening the file in write mode
2file = open('file.txt', 'w')
3
4# writing data into the file
5file.write("Hello, Codebay!")
6
7# closing the file
8file.close()

In the above script, we first open 'file.txt' in 'w' mode, which stands for “write”. If the file does not exist, Python will create it. If the file exists, it will be truncated to zero length before writing. We then call the write() function with our string as the argument.

Finally, it’s good practice to close the file when finished using the close() function. Un-closed files can cause data to be lost or corrupted.

Write Mode

Write mode is denoted by 'w'. If the file exists, write mode will erase all the existing data and start from scratch. If the file does not exist, Python will attempt to create it. Be careful – opening a file in write mode without being aware that the file already contains data might result in data loss.

File Writing with with Statement

The with keyword in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. You don’t have to worry about closing the file as the with statement will automatically take care of it.

1# using with statement for writing to file
2with open('file.txt', 'w') as file:
3    file.write("Hello, Codebay!")

Error Handling

During file operations, several errors can occur, such as IOError when the file can’t be opened, or FileNotFoundError when the file does not exist. Python’s built-in error handling (try/except blocks) is useful here.

1try:
2    with open('file.txt', 'w') as file:
3        file.write("Hello, Codebay!")
4except IOError:
5    print("An IOError has occurred!")
6except FileNotFoundError:
7    print("The file does not exist!")

If an IOError or FileNotFoundError occurs during the file operations, your program will not crash and will instead print your error message.

Note

Always ensure the correct file path is provided while performing write operations to avoid errors.