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 required, the newline character \n
must be manually included.
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, the file "output_file.txt"
is opened, and two lines of text are written to it.
The "w"
mode opens the file for writing. It overwrites the content if the file already exists or creates a new file if it does not.
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, "w"
mode is used to overwrite the file's content, while "a"
mode appends new content to it.
Write string to file
Fill in the blank so that the first line in the output.txt
file contains Hello, World!
after the code is executed.
with open('output.txt', 'w') as file:
file.
('Hello, World!\n')
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result
The document is empty.
Try running the code.