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.
Quick Start & How to Use
- Select a Python example topic from the sidebar menu (or mobile dropdown).
- Examine the structured source code and corresponding expected output.
- Copy code directly or test it in our Online Python Compiler.
- 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 Get the Full Path of the Current Working Directory
Uses os.getcwd.
import os print(os.getcwd() != '')
True
Python File I/O
Write and read text from a file.
with open("out.txt", "w") as f:
f.write("Hello file\n")
with open("out.txt", "r") as f:
print(f.readline().strip())Hello file
Python Program to Find Hash of File
Computes MD5 of file.
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())8d777f385d3dfec8815d20f7496026dc
Python Program to Safely Create a Nested Directory
Creates directories if missing.
from pathlib import Path
Path('nested/dir/path').mkdir(parents=True, exist_ok=True)
print('ok')ok
Python Program to Copy a File
Uses shutil.copyfile.
import shutil
open('a.txt','w').write('hello')
shutil.copyfile('a.txt','b.txt')
print(open('b.txt').read())hello
Python Program Read a File Line by Line Into a List
Reads lines into list.
open('lines.txt','w').write('a\nb\nc')
with open('lines.txt') as f:
lines = [line.strip() for line in f]
print(lines)['a', 'b', 'c']
Python Program to Append to a File
Appends content.
open('append.txt','w').write('start\n')
with open('append.txt','a') as f:
f.write('more\n')
print(open('append.txt').read().strip())start more
Python Program to Extract Extension From the File Name
Uses os.path.splitext.
import os
print(os.path.splitext('archive.tar.gz')[1]).gz
Python Program to Get the File Name From the File Path
Uses os.path.basename.
import os
print(os.path.basename('/a/b/c.txt'))c.txt
Python Program to Get Line Count of a File
Counts lines.
open('c.txt','w').write('x\ny\nz')
print(len(open('c.txt').read().splitlines()))3
Python Program to Find All File with .txt Extension Present Inside a Directory
Uses glob.
import glob
open('d1.txt','w').close()
open('d2.txt','w').close()
print(sorted(glob.glob('*.txt'))[:2])['a.txt', 'b.txt']
Python Program to Get File Creation and Modification Date
Uses os.path.*time.
import os, time
open('time.txt','w').close()
print(os.path.getctime('time.txt') > 0)
print(os.path.getmtime('time.txt') > 0)True True
Python Program to Check the File Size
Uses os.path.getsize.
open('size.txt','w').write('12345')
import os
print(os.path.getsize('size.txt'))5
Python Strings Basics
Concatenate, format, and slice strings.
s = "Hello, Python"
print(s.lower())
print(s.upper())
print(s[0:5])
print(f"Length: {len(s)}")hello, python HELLO, PYTHON Hello Length: 13
Python Program to Find the Square Root
Computes square root using math module.
import math print(math.sqrt(16))
4.0
Python Core Concepts & Decision Breakdown
| Category | Core Concepts | Primary Use Case | Official Docs |
|---|---|---|---|
| Primitives & Basics | int, float, str, bool | Basic arithmetic, logic checks, string formatting | Built-in Types |
| Data Structures | list, tuple, dict, set | Collections, lookup maps, data filtering | Data Structures |
| Control Flow | if/else, for, while, try/except | Iteration, conditional execution, error handling | Control Flow |
| OOP & Modular | def, class, lambda, import | Object orientation, modularization, reusability | Classes & 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
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.