Write Files

Python · File Handling

Theory

Opening a file with mode 'w' prepares it for writing text. If the file does not exist it is created; if it already exists, its contents are erased immediately when the file is opened, before you write anything. f.write(text) writes a string and returns the number of characters written. It does not add a newline for you, so include '\n' yourself, and it only accepts strings, so convert numbers with str() or an f-string.

f.writelines(list_of_strings) writes several strings in one call. Written data is buffered in memory and flushed to disk when the file is closed, which the with statement does for you. A common safe pattern is to write a report: with open('report.txt', 'w') as f: f.write(f'Total sales: {total}\n'). Use mode 'x' instead of 'w' if you want an error rather than an overwrite when the file already exists.

Why we use it

Programs need to save their results - reports, cleaned data, logs and exports - so other people and programs can use them after the script finishes.

When to use it

Use 'w' when you want to create or fully replace a file's content. To add to an existing file use 'a'; to save a DataFrame, df.to_csv() or df.to_excel() is simpler than writing lines by hand.

How it works

  1. with open('report.txt', 'w') as f:
  2. Does report.txt exist? Yes: Erase its content (truncate). No: Create a new empty file.
  3. f.write('Total sales: 5000')
  4. Data sits in a buffer in memory
  5. Block ends: buffer flushed, file closed

Syntax

with open('file.txt', 'w') as f:
    f.write(text)

Example

with open('report.txt', 'w') as f:
    f.write('Total sales: 5000')

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic