Read Files

Python · File Handling

Theory

To read a file you open it with open(path, 'r') (r is the default mode), which returns a file object connected to the file on disk. The with statement, with open('sales.csv') as f:, closes the file automatically when the block ends, even if an error happens inside it. If the file does not exist, open() raises FileNotFoundError.

There are several ways to get the content. f.read() returns the whole file as one string; f.readline() returns the next single line; f.readlines() returns a list of all lines, each ending in '\n'; and looping, for line in f:, reads one line at a time, which is the most memory-friendly choice for big files. Add encoding='utf-8' to read text with Hindi names or special symbols reliably, and use line.strip() to remove the trailing newline.

Why we use it

Most real data lives in files - CSV exports, logs, config and text documents. Reading files is how a Python program gets that data in so it can be cleaned, analysed or transformed.

When to use it

Use open() for plain text, logs and custom formats. For tabular data such as CSV or Excel, pd.read_csv() or pd.read_excel() is usually better because it parses columns and types for you.

How it works

  1. with open('sales.csv') as f:
  2. Does the file exist? Yes: Get a file object f. No: Raise FileNotFoundError.
  3. Is the file large? Yes: Loop: for line in f. No: f.read() the whole content.
  4. Process the text
  5. Block ends, file closes automatically

Syntax

with open('file.txt', 'r') as f:
    data = f.read()

Example

with open('sales.csv', 'r') as f:
    print(f.read())

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