In Python, writing text to a file is a fundamental operation that often comes up in various programming tasks. Whether you’re working with data processing, log files, or generating reports, the ability to write text to a file is essential. In this blog post, we will explore how to write text to a file in Python.
Writing to a File
The provided code opens a file named ‘memo.txt’ in write mode using the open() function and assigns the file handle to the variable f. It then writes three lines of text to the file using the writelines() method of the file handle f. Each line is terminated by the newline character \n. Finally, it prints a message indicating that the text has been written to the file.
It also uses the with statement to automatically close the file when the block is exited and includes error handling code to catch any IOError exceptions that may occur. It is a good practice to use the with statement when working with files because it ensures that the file is properly closed even if an exception is raised within the block.
filename:str = 'memo.txt'
# Use 'with' statement to automatically close file when done
try:
with open(filename, 'w') as f:
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
f.writelines(lines)
print('Text written to file', filename)
except IOError:
print(f"Error: could not write to file '{filename}'")
If the file ‘memo.txt’ already exists, opening it in write mode will overwrite the existing contents of the file. If the file does not exist, it will be created.
Conclusion
If you’re interested in learning how to read from files in Python, be sure to check out another one of my articles titled Reading Files with Python: An Example Program. I hope that’s been informative to you. If you wish to learn more about Python, please subscribe to our newsletter today and continue your Python learning journey with us!