Working with Files: Write to a Text File in Python
We learned how to read from a file in Python in the previous article and in this one, you will be learning another fundamental operation which is to write to a file and read the contents of it and perform actions based on that.
You must've learned about Python's syntax, functions, and operators in the previous articles but in this article, you will learn about the basic operation of writing to a text file in Python. So, without any delay, let's get started.
Procedure for Writing to a text file in Python:
Writing to a text file in Python involves a few steps and you will be using built-in functions like 'open()', 'write()', and 'close()'.
Here's a detailed explanation of how to do it:
- Open the file: To read from a text file, you first need to open it using the 'open()' function. This function takes two arguments: the file path and the mode in which you want to open the file. To write to a file, you should pass the mode as 'w', which stands for write. If the file doesn't exist, it will be created. If it already exists, its previous contents will be overwritten. Here's an example:
>>> file_path = 'path/to/your/file.txt'
>>> file = open(file_path, 'w')
- Write to the file: Once you have opened the file, you can write to it using the 'write()' method, which is available on the file object. This method takes a string argument and writes it to the file. Here's an example:
>>> file.write("Hello, World!")
>>> file.write("This is a sample text.")
- Close the file: After you have finished reading the file, it's good practice to close it using the 'close()' method. This will free up system resources. Here's an example:
>>> file.close()
Alternatively, you can use a context manager ('with' statement) to automatically handle the closing of the file instead of manually closing it each and everytime. Here's an example:
>>> file_path = 'path/to/your/file.txt'
>>> with open(file_path, 'w') as file:
>>> file.write("Hello, World!")
>>> file.write("This is a sample text.")
Since I used 'with' statement here, I don't have to manually close the file, it will get closed automatically. Also, this method ensures that the file is properly closed even if an exception occurs.
NOTE: Remember to replace 'path/to/your/file.txt' with the actual file path on your system. Make sure to provide the correct path, including the file name and extension.
Conclusion:
In conclusion, writing to a file in Python allows you to store and persist data for later use or share information with other programs. By utilizing the open() function and appropriate file object methods, such as write(), you can write to a text file either as a single string or as individual lines.