Fundamentals 17 min read

Master Python File I/O and System Scripting with 10 Practical Exercises

This guide walks you through Python's built‑in open() function, file modes, reading and writing techniques, directory traversal with os.walk, and a series of practical scripts including a triangle printer, number‑guessing game, log analysis, IP counting, prime number generator, command‑line argument handling, web page fetching, process memory aggregation, port monitoring, and SNMP‑based CPU and network traffic monitoring.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python File I/O and System Scripting with 10 Practical Exercises

Python provides the built‑in open('file_name', mode, buffering) function to obtain a file object; using modes such as 'r', 'w', 'a', 'r+', 'w+', 'a+', and their binary variants ( 'rb', 'wb', etc.) determines how data is accessed and whether the file is created.

Common file operations include: f.read([size]) – reads the whole file or a specific number of bytes. f.readline() – returns a single line. for line in f: – iterates over lines. f.write('text') – writes a string (convert other data to string first). f.tell() – returns the current file pointer position. f.seek(offset, whence) – moves the file pointer; whence can be 0 (start), 1 (current), or 2 (end). f.close() – closes the file.

1. List all files in a directory tree

#!/usr/bin/env python
import os
for root, dirs, files in os.walk('/tmp'):
    for name in files:
        print(os.path.join(root, name))

2. Print a right‑angled triangle

#!/usr/bin/env python
n = int(raw_input('input number:'))
for i in range(n):
    for j in range(i + 1):
        print '*',
    print '
'

3. Number‑guessing game that prints a triangle on success

#!/usr/bin/env python
import random
while True:
    guess = int(raw_input('input number:'))
    target = random.randint(1, 10)
    if guess == target:
        for i in range(guess):
            for j in range(i):
                print '*',
            print '
'
    else:
        print 'please input number again'

4. Create a daily log file and write disk usage

#!/usr/bin/env python
import time, os
date_str = time.strftime('%Y-%m-%d')
log = open(date_str + '.log', 'w')
log.write(''.join(os.popen('df -h').readlines()))
log.close()

5. Count visits per IP from a log file

#!/usr/bin/env python
ip_counts = {}
with open('/tmp/1.log') as f:
    for line in f:
        ip = line.split()[0]
        ip_counts[ip] = ip_counts.get(ip, 0) + 1
for ip, cnt in ip_counts.items():
    print '%s : %s' % (ip, cnt)

6. Validate numeric input and print all primes up to that number

#!/usr/bin/env python
while True:
    try:
        n = int(raw_input('请输入数字:').strip())
        break
    except ValueError:
        print('你输入的不是数字,请重新输入:')
for i in range(2, n + 1):
    for x in range(2, i):
        if i % x == 0:
            break
    else:
        print i

7. Demonstrate sys.argv usage

#!/usr/bin/env python
import sys
if len(sys.argv) < 2:
    print "No function be setted."
    sys.exit()
option = sys.argv[1][1:]
if option == 'version':
    print "Version1.2"
elif option == 'help':
    print "enter a filename to see the context of it!"
else:
    for filename in sys.argv[1:]:
        with open(filename) as f:
            for line in f:
                print line,

8. Simple web page fetch and first/last line extraction

from urllib import urlretrieve

def firstNonBlank(lines):
    for eachLine in lines:
        if eachLine.strip():
            return eachLine

def firstLast(webpage):
    f = open(webpage)
    lines = f.readlines()
    f.close()
    print firstNonBlank(lines)
    lines.reverse()
    print firstNonBlank(lines)

def download(url='http://www.magedu.com/72446.html', process=firstLast):
    try:
        retval = urlretrieve(url)[0]
    except IOError:
        retval = None
    if retval:
        process(retval)

if __name__ == '__main__':
    download()

9. Iterate through a directory and delete specific files

#!/usr/bin/env python
import os

def fr(dir):
    for root, dirs, files in os.walk(dir):
        for f in files:
            if f == "1.txt":
                os.remove(os.path.join(root, f))
            else:
                fr(os.path.join(root, f))

10. Sum memory usage of all processes (RSS column)

#!/usr/bin/env python
import os
lines = os.popen('ps aux').readlines()
mem_vals = []
for line in lines[1:]:
    rss = int(line.split()[5])
    mem_vals.append(rss)
print 'Total RSS:', sum(mem_vals)

11. Monitor port 80, restart httpd if closed, and send email alert

#!/usr/bin/env python
import os, time, sys, smtplib
from email.mime.text import MIMEText

def sendsimplemail(warning):
    msg = MIMEText(warning)
    msg['Subject'] = 'python first mail'
    msg['From'] = 'root@localhost'
    smtp = smtplib.SMTP()
    smtp.connect(r'smtp.126.com')
    smtp.login('user', 'pass')
    smtp.sendmail('user', ['user'], msg.as_string())
    smtp.close()

while True:
    status = os.popen('netstat -tulnp | grep httpd').readlines()
    if not status:
        os.system('service httpd start')
        sendsimplemail('httpd failed to start')
    else:
        print 'httpd running'
    time.sleep(5)

12. SNMP‑based CPU usage monitoring for multiple hosts

#!/usr/bin/env python
import os

def getAllitems(host, oid):
    return os.popen('snmpwalk -v 2c -c public %s %s' % (host, oid)).read().split('
')[:-1]

def getDate(host):
    items = getAllitems(host, '.1.3.6.1.4.1.2021.11')
    total = sum(float(item.split()[3]) for item in items)
    rates = []
    for item in items:
        rates.append(float(item.split()[3]) / total * 100)
    labels = ['%us','%ni','%sy','%id','%wa','%cpu_irq','%cpu_sIRQ']
    return list(zip(rates, labels))

if __name__ == '__main__':
    hosts = ['192.168.10.1','192.168.10.2']
    for host in hosts:
        print '==========%s==========' % host
        for val, label in getDate(host):
            print ' %.2f%s' % (val, label)

13. SNMP‑based network interface traffic monitoring

#!/usr/bin/env python
import os, re

def getAllitems(host, oid):
    return os.popen('snmpwalk -v 2c -c public %s %s' % (host, oid)).read().split('
')[:-1]

def getDevices(host):
    descr = getAllitems(host, 'RFC1213-MIB::ifDescr')
    return [item.split(':')[3].strip() for item in descr if re.search('eth', item)]

def getDate(host, oid):
    data = getAllitems(host, oid)[1:]
    return [str(round(float(item.split(':')[3].strip())/1024,2)) + ' KB' for item in data]

if __name__ == '__main__':
    hosts = ['192.168.10.1','192.168.10.2']
    for host in hosts:
        devs = getDevices(host)
        in_octets = getDate(host, 'IF-MIB::ifInOctets')
        out_octets = getDate(host, 'IF-MIB::ifOutOctets')
        print '==========%s==========' % host
        for i in range(len(devs)):
            print '%s : RX: %-15s   TX: %s' % (devs[i], in_octets[i], out_octets[i])

These examples collectively demonstrate essential Python file handling, command‑line processing, system monitoring, and network management techniques useful for beginners and intermediate developers.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

monitoringPythonNetworkingosfile-iosys
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.