0
0
Pythonprogramming~5 mins

Writing file data in Python

Choose your learning style9 modes available
Introduction

Writing file data lets you save information on your computer so you can use it later.

Saving notes or documents you create in a program.
Logging events or errors while a program runs.
Storing user settings or preferences.
Exporting data from a program to share with others.
Backing up important information automatically.
Syntax
Python
with open('filename.txt', 'w') as file:
    file.write('Your text here')

The 'w' mode means write. It creates a new file or replaces an old one.

Using with automatically closes the file when done.

Examples
This writes 'Hello world!' into a file named notes.txt.
Python
with open('notes.txt', 'w') as file:
    file.write('Hello world!')
This writes three lines of text separated by newlines.
Python
with open('data.txt', 'w') as file:
    file.write('Line 1\nLine 2\nLine 3')
This creates an empty file or clears an existing one.
Python
with open('empty.txt', 'w') as file:
    pass
Sample Program

This program writes two lines of greeting text into a file named greeting.txt and then prints a confirmation message.

Python
filename = 'greeting.txt'
with open(filename, 'w') as file:
    file.write('Hi there!\nWelcome to file writing.')

print(f"Data written to {filename}")
OutputSuccess
Important Notes

If the file already exists, writing with 'w' will erase its old content.

To add text without erasing, use 'a' mode (append) instead of 'w'.

Always use with to safely open and close files.

Summary

Use open with 'w' mode to write data to a file.

Writing replaces old content unless you append.

with helps manage files safely and easily.