Files and I/O Examples
Read and write files, inspect paths, list directory contents, and compute file hashes. These examples cover real-world tasks you’ll use in automation scripts and everyday data processing.
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'))
Output
c.txt
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())
Output
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())
Output
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')
Output
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())
Output
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)
Output
['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())
Output
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])
Output
.gz
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()))
Output
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])
Output
['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)
Output
True True
Python Program to Get the Full Path of the Current Working Directory
Uses os.getcwd.
import os print(os.getcwd() != '')
Output
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'))
Output
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)}")
Output
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))
Output
4.0
Keep Practicing
Use the online Python compiler to run examples and test variations. Reinforce learning by building small scripts for each topic.
FAQ
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, 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.