Quick Answer

Different methods for file writing.

Understanding the Issue

Python provides various ways to write data to files, each suited for different scenarios.

The Problem

This code demonstrates the issue:

Python Error
data = ["line1", "line2", "line3"]
# Need to write to file

The Solution

Here's the corrected code:

Python Fixed
# Method 1: Write string
with open("file.txt", "w") as f:
    f.write("Hello World")

# Method 2: Write multiple lines
with open("file.txt", "w") as f:
    f.writelines(data)

# Method 3: Append mode
with open("file.txt", "a") as f:
    f.write("New line
")

# Method 4: Using print
with open("file.txt", "w") as f:
    print("Formatted output", file=f)

# Method 5: Binary mode
with open("file.bin", "wb") as f:
    f.write(b"binary data")

Key Takeaways

Specify the correct mode (w, a, wb) based on use case.