Master Python: List Files, Print Patterns, and Build Simple Utilities
This article presents five practical Python scripts that demonstrate how to traverse directories and list files, draw text triangles, create a number‑guessing game, log disk usage, and analyze IP access counts from log files, each explained with clear code examples.
1. List Files in Current and Subdirectories
Use Python's os.walk to enumerate all files under a given directory and print their absolute paths.
#!/usr/bin/env python
import os
for root, dirs, files in os.walk('/tmp'):
for name in files:
print(os.path.join(root, name))The os.walk function returns a tuple (dirpath, dirnames, filenames) for each directory.
2. Print a Text Triangle
A simple script that asks for a number and prints a left‑aligned triangle of asterisks.
#!/usr/bin/env python
input = int(raw_input('input number:'))
for i in range(input):
for j in range(i):
print '*',
print '
'3. Number Guessing Game
The program generates a random digit, prompts the user to guess, and prints a triangle on success; otherwise it asks to try again.
#!/usr/bin/env python
import random
while True:
input = int(raw_input('input number:'))
random_num = random.randint(1, 10)
print input, random_num
if input == random_num:
for i in range(input):
for j in range(i):
print '*',
print '
'
else:
print 'please input number again'4. Generate Disk Usage Log File
This script captures the output of df -h, formats it, and writes it to a log file named with the current date.
#!/usr/bin/env python
#!coding=utf-8
import time
import os
new_time = time.strftime('%Y-%m-%d')
disk_status = os.popen('df -h').readlines()
str1 = ''.join(disk_status)
f = file(new_time + '.log', 'w')
f.write('%s' % str1)
f.flush()
f.close()5. Count IP Accesses from a Log File
Read a log file, extract IP addresses, and print how many times each IP appears.
#!/usr/bin/env python
#!coding=utf-8
ip_list = []
f = file('/tmp/1.log')
lines = f.readlines()
f.close()
for line in lines:
ip = line.split()[0]
ip_list.append(ip)
unique_ips = set(ip_list)
for ip in unique_ips:
count = ip_list.count(ip)
print '%s : %s' % (ip, count)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
