System Scripting Lab 09

Python File I/O

Setup

mkdir lab09
cd lab09
idle3

Exercise 1: Directory Operations

import os

# Print current working directory
print("Current Directory:", os.getcwd())

# Check if directory exists
path = "/usr/local/"

if os.path.exists(path):
    os.chdir(path)
    print("Changed to:", os.getcwd())

    # List contents
    for item in os.listdir():
        print(item)
else:
    print("Directory does not exist")

Key Functions:

Exercise 2: Create Folders and Files

import os

# Create main folder
os.makedirs("share/bit", exist_ok=True)
os.makedirs("share/coin", exist_ok=True)
os.makedirs("share/crypto", exist_ok=True)

# Create files in coin folder
files = ["file1.txt", "file2.txt", "file3.txt"]

for f in files:
    open(f"share/coin/{f}", "w").close()

# List files
for file in os.listdir("share/coin"):
    print(file)

Exercise 3: Directory Size Calculator

import os

while True:
    directory = input("Enter directory (or 'stop' to exit): ")

    if directory == "stop":
        break

    # Convert to absolute path
    path = os.path.abspath(directory)

    if not os.path.exists(path):
        print("Directory does not exist")
        continue

    total_size = 0

    for item in os.listdir(path):
        full_path = os.path.join(path, item)

        if os.path.isfile(full_path):
            total_size += os.path.getsize(full_path)

    print("Total size:", total_size, "bytes")

Key Concepts:

Exercise 4: Write Directory Files to Text File

import os

path = "/etc/default/"

# Check existence
if os.path.exists(path):

    # Delete file if exists
    if os.path.exists("fileNames.txt"):
        os.remove("fileNames.txt")

    # Write filenames
    with open("fileNames.txt", "w") as f:
        for file in os.listdir(path):
            f.write(file + "\n")

    # Read and display
    with open("fileNames.txt", "r") as f:
        for line in f:
            print(line.strip())
else:
    print("Directory not found")

Exercise 5: File Write and Read with Functions

# Function to create and write file
def write_file(filename):
    # Delete if exists
    import os
    if os.path.exists(filename):
        os.remove(filename)

    # Write content
    with open(filename, "w") as f:
        f.write("When I think about my programming abilities\n")
        f.write("It seems that I am very foreign to this sort of thing\n")
        f.write("I see that the problem lies on my lack of concentration and desire for the Internet\n")
        f.write("How can I redeem myself from this dilemma\n")
        f.write("I should course myself and sit up for the future\n")
        f.write("Hard work results to success.\n")

    print("File written successfully")

# Function to read specific lines
def read_file(filename):
    with open(filename, "r") as f:
        for line in f:
            if line.startswith(("When", "I", "Hard")):
                print(line.strip())

# Interactive usage
filename = input("Enter filename: ")

if filename != "end":
    write_file(filename)
    read_file(filename)

Key Concepts:

Key Exam Tips