Master Python File Operations and System Automation with Practical Code Examples
This article presents a comprehensive collection of Python tutorials and scripts covering file I/O modes, directory traversal, log analysis, simple games, command‑line argument handling, process monitoring, port checking, authentication loops, and SNMP‑based CPU and network traffic monitoring, providing a solid foundation for automation and operations tasks.
File Operations in Python
Python provides the built‑in open() function to open files in various modes such as r, w, a, r+, w+, a+ and their binary equivalents ( rb, wb, etc.). The function returns a file object that supports methods like read(), readline(), write(), tell(), seek() and close().
Common File‑Handling Examples
Listing files in a directory and printing absolute paths:
import os
for root, dirs, files in os.walk('/tmp'):
for name in files:
print(os.path.join(root, name))Printing a triangle of asterisks:
n = int(raw_input('input number:'))
for i in range(n):
for j in range(i):
print '*',
print '
'Simple number‑guessing game that creates a log file named with the current date:
import random, time, os
new_time = time.strftime('%Y-%m-%d')
f = open(new_time + '.log', 'w')
# ... write log ...Log Analysis and Statistics
Counting IP address occurrences from a log file:
list = []
with open('/tmp/1.log') as f:
for line in f:
ip = line.split()[0]
list.append(ip)
for ip in set(list):
print '%s : %s' % (ip, list.count(ip))Prime Number Generator
while True:
try:
n = int(raw_input('请输入数字:').strip())
for i in range(2, n+1):
for x in range(2, i):
if i % x == 0:
break
else:
print i
except ValueError:
print('你输入的不是数字,请重新输入:')Web Page Retrieval
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)Command‑Line Argument Usage
Using sys.argv to display file contents, version or help information.
Directory Traversal and File Deletion
import os
def fr(dir):
filelist = os.listdir(dir)
for i in filelist:
fullfile = os.path.join(dir, i)
if not os.path.isdir(fullfile):
if i == "1.txt":
os.remove(fullfile)
else:
fr(fullfile)Process Memory Summation
import os
lines = os.popen('ps aux').readlines()
rss = [int(line.split()[5]) for line in lines[1:]]
print sum(rss)Port Monitoring and Email Notification
import os, time, smtplib
while True:
http_status = os.popen('netstat -tulnp | grep httpd').readlines()
if not http_status:
os.system('service httpd start')
# send email if needed
time.sleep(5)Simple Authentication Loop
while True:
user = raw_input('Please input your username:')
if user == "wenlong":
pwd = raw_input('Please input your pass:')
while pwd != '123':
pwd = raw_input('Please input your pass again:')
print 'welcome to select system!'CPU Monitoring via SNMP
def getAllitems(host, oid):
return os.popen('snmpwalk -v 2c -c public %s %s' % (host, oid)).read().split('
')[:-1]
# ... calculate usage percentages ...Network Interface Traffic Monitoring
def getDevices(host):
mib = getAllitems(host, 'RFC1213-MIB::ifDescr')
return [item.split(':')[3].strip() for item in mib if re.search('eth', item)]
# ... retrieve in/out octets and print ...The script collection demonstrates essential Python techniques for file I/O, directory traversal, log processing, system monitoring, network traffic collection and basic user interaction, providing a practical foundation for automation and operations tasks.
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.
