Just as you can read data from files, Python also allows you to write data to files. This is essential for saving program output, storing user-generated content, or creating configuration files.
To write to a file, you need to open it in a mode that permits writing. The primary mode for this is 'w'
. You use it with the open()
function, similar to how you used 'r'
for reading:
# Open 'output.txt' in write mode
# If 'output.txt' exists, its contents will be erased!
# If it doesn't exist, it will be created.
file_object = open('output.txt', 'w')
# ... perform write operations ...
file_object.close() # Remember to close
Important: Opening a file in 'w'
mode has a significant side effect. If the file already exists, its entire contents are immediately erased. If the file doesn't exist, Python will create it for you. Be very careful when using 'w'
mode to avoid accidental data loss.
As with reading, using the with
statement is the recommended way to handle files, as it automatically takes care of closing the file, even if errors occur:
# Preferred way: Using 'with'
with open('output.txt', 'w') as f:
# 'f' is our file object, ready for writing
pass # We'll add write operations here
# File is automatically closed when exiting the 'with' block
write()
MethodOnce a file is opened in write mode (or append mode, discussed later), you can write string data to it using the file object's write()
method. This method takes a single string argument and writes it to the file at the current position.
Let's write a simple sentence to a file named greeting.txt
:
# Define the text we want to write
message = "Hello from Python!\n" # Note the newline character \n
try:
# Open the file in write mode using 'with'
with open('greeting.txt', 'w') as f:
f.write(message) # Write the string to the file
print("Successfully wrote to greeting.txt")
# Optional: Verify by reading the file back
with open('greeting.txt', 'r') as f:
content = f.read()
print("File content:")
print(content)
except IOError as e:
print(f"An error occurred: {e}")
If you run this code, it will:
greeting.txt
in the same directory as your script."Hello from Python!\n"
into that file.Notice the \n
at the end of the message
string. This is the newline character. The write()
method does not automatically add a newline after writing the string. If you want subsequent writes to appear on a new line, you must explicitly include \n
in the string you are writing.
If you need to write multiple lines of text, you have a couple of options:
Multiple write()
calls: Call write()
for each line, ensuring each string ends with \n
.
lines_to_write = [
"First line.\n",
"Second line.\n",
"Third line.\n"
]
try:
with open('multiple_lines.txt', 'w') as f:
for line in lines_to_write:
f.write(line) # Write each line including its newline
print("Successfully wrote multiple lines.")
except IOError as e:
print(f"An error occurred: {e}")
This creates multiple_lines.txt
with each string from the list on its own line.
Using writelines()
: This method takes a list (or any iterable) of strings and writes each string to the file. Like write()
, it does not add newline characters automatically; your strings must already contain them if needed.
lines_to_write = [
"Report Header\n",
"--------------\n",
"Data point 1: Value A\n",
"Data point 2: Value B\n"
]
try:
with open('report.txt', 'w') as f:
f.writelines(lines_to_write) # Write all strings from the list
print("Successfully wrote report using writelines().")
except IOError as e:
print(f"An error occurred: {e}")
This achieves the same result as the loop method but can be slightly more concise for lists of strings already formatted with newlines.
The write()
method strictly requires a string argument. If you have data of other types, like numbers (integers or floats), you must convert them to strings using str()
before writing.
item = "Widget"
quantity = 15
price = 29.95
total_cost = quantity * price
try:
with open('order_summary.txt', 'w') as f:
f.write("Order Summary\n")
f.write("=============\n")
f.write("Item: " + item + "\n")
f.write("Quantity: " + str(quantity) + "\n") # Convert integer to string
f.write("Price per item: $" + str(price) + "\n") # Convert float to string
f.write("Total Cost: $" + str(total_cost) + "\n") # Convert float to string
print("Successfully wrote order summary.")
except IOError as e:
print(f"An error occurred: {e}")
In this example, quantity
, price
, and total_cost
are numeric types. We use str()
to convert them into strings so they can be concatenated with other strings and written to the file using f.write()
.
Remember, writing to files is a common operation. Always use the with
statement to ensure files are handled correctly, and be mindful of the 'w'
mode's behavior of overwriting existing files. In the next section, we'll look at how to add data to a file without erasing its previous content.
© 2025 ApX Machine Learning