Files and I/O Examples

Key Takeaway: Practice Python with 110+ runnable examples covering strings, lists, dicts, math, dates, OOP, and file I/O — complete with expected terminal outputs.

Audience & Use Case: Designed for computer science students, data analysts, backend developers, and job seekers preparing for Python technical interviews.

Last updated: October 2026 110 Verified Examples

Quick Start & How to Use

  1. Select a Python example topic from the sidebar menu (or mobile dropdown).
  2. Examine the structured source code and corresponding expected output.
  3. Copy code directly or test it in our Online Python Compiler.
  4. Experiment by tweaking variables, loops, and conditions to deepen your understanding.

Who is this for: Beginners, interview candidates, and developers looking for reliable code snippets.

Credible Resources:Python Tutorial · Python Compiler · Python 3 Official Documentation · JavaScript Examples

Python Program to Find All File with .txt Extension Present Inside a Directory

Uses glob.

Source Code
import glob
open('d1.txt','w').close()
open('d2.txt','w').close()
print(sorted(glob.glob('*.txt'))[:2])
Expected Output
['a.txt', 'b.txt']

Python File I/O

Write and read text from a file.

Source Code
with open("out.txt", "w") as f:
    f.write("Hello file\n")

with open("out.txt", "r") as f:
    print(f.readline().strip())
Expected Output
Hello file

Python Program to Find Hash of File

Computes MD5 of file.

Source Code
import hashlib
with open('tmp.txt','w') as f: f.write('data')
m = hashlib.md5()
with open('tmp.txt','rb') as f:
    for chunk in iter(lambda: f.read(8192), b''):
        m.update(chunk)
print(m.hexdigest())
Expected Output
8d777f385d3dfec8815d20f7496026dc

Python Program to Safely Create a Nested Directory

Creates directories if missing.

Source Code
from pathlib import Path
Path('nested/dir/path').mkdir(parents=True, exist_ok=True)
print('ok')
Expected Output
ok

Python Program to Copy a File

Uses shutil.copyfile.

Source Code
import shutil
open('a.txt','w').write('hello')
shutil.copyfile('a.txt','b.txt')
print(open('b.txt').read())
Expected Output
hello

Python Program Read a File Line by Line Into a List

Reads lines into list.

Source Code
open('lines.txt','w').write('a\nb\nc')
with open('lines.txt') as f:
    lines = [line.strip() for line in f]
print(lines)
Expected Output
['a', 'b', 'c']

Python Program to Append to a File

Appends content.

Source Code
open('append.txt','w').write('start\n')
with open('append.txt','a') as f:
    f.write('more\n')
print(open('append.txt').read().strip())
Expected Output
start
more

Python Program to Extract Extension From the File Name

Uses os.path.splitext.

Source Code
import os
print(os.path.splitext('archive.tar.gz')[1])
Expected Output
.gz

Python Program to Get the File Name From the File Path

Uses os.path.basename.

Source Code
import os
print(os.path.basename('/a/b/c.txt'))
Expected Output
c.txt

Python Program to Get Line Count of a File

Counts lines.

Source Code
open('c.txt','w').write('x\ny\nz')
print(len(open('c.txt').read().splitlines()))
Expected Output
3

Python Program to Get File Creation and Modification Date

Uses os.path.*time.

Source Code
import os, time
open('time.txt','w').close()
print(os.path.getctime('time.txt') > 0)
print(os.path.getmtime('time.txt') > 0)
Expected Output
True
True

Python Program to Get the Full Path of the Current Working Directory

Uses os.getcwd.

Source Code
import os
print(os.getcwd() != '')
Expected Output
True

Python Program to Check the File Size

Uses os.path.getsize.

Source Code
open('size.txt','w').write('12345')
import os
print(os.path.getsize('size.txt'))
Expected Output
5

Python Strings Basics

Concatenate, format, and slice strings.

Source Code
s = "Hello, Python"
print(s.lower())
print(s.upper())
print(s[0:5])
print(f"Length: {len(s)}")
Expected Output
hello, python
HELLO, PYTHON
Hello
Length: 13

Python Program to Find the Square Root

Computes square root using math module.

Source Code
import math
print(math.sqrt(16))
Expected Output
4.0

Python Core Concepts & Decision Breakdown

CategoryCore ConceptsPrimary Use CaseOfficial Docs
Primitives & Basicsint, float, str, boolBasic arithmetic, logic checks, string formattingBuilt-in Types
Data Structureslist, tuple, dict, setCollections, lookup maps, data filteringData Structures
Control Flowif/else, for, while, try/exceptIteration, conditional execution, error handlingControl Flow
OOP & Modulardef, class, lambda, importObject orientation, modularization, reusabilityClasses & OOP

Keep Practicing

Use the online Python compiler to run examples and test variations. Reinforce learning by building small scripts for each topic.

Frequently Asked Questions

Python is a high-level, interpreted programming language known for readable syntax. Practicing with runnable examples accelerates learning by reinforcing concepts through immediate feedback.

You can run all examples instantly using our integrated Online Python Compiler directly in your web browser without downloading any software.

Yes. The programs cover foundational topics including arithmetic, strings, lists, dictionaries, recursion, algorithms, and file operations commonly tested in coding interviews.

Yes. All snippets use standard Python 3 syntax and libraries, ensuring cross-platform compatibility across Windows, macOS, Linux, and web-based environments.

Learn Python by Practicing Examples

Hands-on practice is the fastest way to understand Python. Each example focuses on a single concept—from variables, strings, lists, and dictionaries to loops, functions, classes, exceptions, and file I/O. Modify examples, add new functions, and see how clean design leads to readable, maintainable code.

Use our tools to deepen learning: the Python Compiler to run snippets, the Python Official Docs for language standards, and the Python Tutorial for structured lessons.

Beginner-Friendly

Start with variables, operators, and control flow. Build confidence with small, readable programs.

Practical Patterns

Practice lists, dicts, comprehensions, functions, classes, exceptions, and file handling.

Grow Skills

Explore generators and decorators to write expressive, reusable code.