How to Write Data to a File
In this lesson, we will explore methods such as write()
and writelines()
to write data to a file.
Writing Strings with write()
The write()
method is used to simply record a string to a file.
To use it, the file needs to be opened in "w"
mode.
If line breaks are needed within the file, you need to include the line break character \n
yourself.
Using write()
with open("output_file.txt", "w+") as file:
file.write("First line\n")
file.write("Second line\n")
# Output the file content
file.seek(0)
print(file.read())
In the code above, a file named "output_file.txt"
is opened and two lines of strings are recorded.
The "w"
mode is the writing mode, it overwrites the content if the file already exists and creates a new file if it doesn’t.
The "w+"
mode allows both reading and writing, performing all file operations.
The write()
method writes string data to the file, and a line break character \n
must be included at the end of each line.
seek(0)
moves the file pointer (the position for reading and writing) to the beginning of the file.
Finally, the read()
method reads the file’s content and prints it.
Writing Multiple Lines at Once with writelines()
The writelines()
method records a list of strings to a file at once.
Similarly, to have line breaks between the input contents, \n
should be added at the end of each line.
Using writelines()
lines = ["First line.\n", "Second line.\n", "Third line.\n"]
with open("output_file.txt", "w") as file:
file.writelines(lines)
In this example, the lines
list containing multiple lines of strings is written to the "output_file.txt"
file all at once.
Just like with write()
, line break characters should be included at the end of each line.
File Writing Modes Reference
When writing content to a file, use "w"
mode to completely overwrite the existing file, or "a"
mode to add content to the existing file.
"w"
(write mode): Creates a new file or overwrites an existing file. If the file already exists, its content is erased."a"
(append mode): Adds new data to an existing file. Creates a new file if it doesn’t exist.
File Writing Modes Example
# Assuming "output_file.txt" contains "Hello"
# Overwriting the existing content with write mode
with open("output_file.txt", "w") as file:
file.write("w\n")
# Content of output_file.txt
# w
# Adding to existing content with append mode
with open("output_file.txt", "a") as file:
file.write("a\n")
# Content of output_file.txt
# w
# a
In this example, the "w"
mode is used to overwrite the existing content of the file, and the "a"
mode is used to add new content to the existing file.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.