WRITING TO FILES - Creating and writing content to files
Python
#!/usr/bin/env python3
"""
WRITING TO FILES - Creating and writing content to files
Demonstrates different ways to write data to files
"""
import os
import tempfile
print("=" * 60)
print("WRITING TO FILES - Creating New Files")
print("=" * 60)
temp_dir = tempfile.gettempdir()
# Example 1: Basic write mode ('w')
print("\n1. Write Mode 'w' - Creates New or Overwrites")
print("-" * 40)
file1 = os.path.join(temp_dir, "write_example.txt")
f = open(file1, 'w')
f.write("First line of text\n")
f.write("Second line of text\n")
f.write("Third line of text\n")
f.close()
print(f"Created: {file1}")
f = open(file1, 'r')
print("Content:")
print(f.read())
f.close()
# Example 2: Overwriting existing file
print("\n2. Writing Again Overwrites Content")
print("-" * 40)
f = open(file1, 'w')
f.write("This completely replaces the old content\n")
f.close()
f = open(file1, 'r')
print("New content:")
print(f.read())
f.close()
# Example 3: Writing multiple lines with writelines()
print("\n3. Using writelines() for Multiple Lines")
print("-" * 40)
file2 = os.path.join(temp_dir, "writelines_example.txt")
lines_to_write = [
"Apple\n",
"Banana\n",
"Cherry\n",
"Date\n"
]
f = open(file2, 'w')
f.writelines(lines_to_write)
f.close()
print(f"Created: {file2}")
f = open(file2, 'r')
print("Content:")
print(f.read())
f.close()
# Example 4: Writing without newlines
print("\n4. Writing Without Explicit Newlines")
print("-" * 40)
file3 = os.path.join(temp_dir, "no_newlines.txt")
f = open(file3, 'w')
f.write("One")
f.write("Two")
f.write("Three")
f.close()
f = open(file3, 'r')
print("Content (all on one line):")
print(f.read())
f.close()
# Example 5: Writing numbers and other types
print("\n5. Writing Non-String Data (Must Convert)")
print("-" * 40)
file4 = os.path.join(temp_dir, "numbers.txt")
f = open(file4, 'w')
numbers = [1, 2, 3, 4, 5]
for num in numbers:
f.write(str(num) + "\n")
f.close()
f = open(file4, 'r')
print("Content:")
print(f.read())
f.close()
# Cleanup
for f in [file1, file2, file3, file4]:
if os.path.exists(f):
os.remove(f)
print("\n" + "=" * 60)
print("Key Points:")
print(" - Mode 'w' creates new file or overwrites existing")
print(" - write() writes a single string")
print(" - writelines() writes a list of strings")
print(" - Must convert non-strings to strings first")
print(" - Must add '\\n' manually for newlines")
print("=" * 60)