Member-only story
Writing data to files is a fundamental task in programming, and Python makes it incredibly easy. Whether you’re a beginner or an experienced coder, understanding how to write to files can save you time and effort in various scenarios.
In this article, we’ll explore the basics of file writing in Python, covering different file modes, writing strings, and writing lists or dictionaries to files.
Writing Strings to a File
To write a string to a file in Python, you can use the open()
function along with the write()
method. Here's an example:
# Open a file in write mode
file = open("example.txt", "w")
# Write a string to the file
file.write("This is a sample line of text.")
# Close the file
file.close()
In this code snippet, we open a file named example.txt
in write mode ("w"
). If the file doesn't exist, it will be created. We then use the write()
method to write a string to the file. Finally, we close the file to ensure that the data is properly saved.