JustPaste
HomeCategoriesAboutDonateContactTerms of UsePrivacy Policy
JustPaste

Free online notepad — write and share instantly

Navigate

  • Home
  • Timeline
  • Categories

Info

  • About
  • Donate
  • Contact

Legal

  • Terms of Use
  • Privacy Policy

© 2026 JustPaste.app. All rights reserved.

Made with ♥ by JustPaste

Untitled Page | JustPaste.app
9 days ago5 views
👨‍💻Programming
#!/usr/bin/env python3
# Lab 1: Intro to Python (Beginner Edition)
# Run with: python3 lab1.py
import os
import datetime

def display_myfile():
    """Print the contents of myfile.txt."""
    filename = "myfile.txt"
    try:
        with open(filename, "r", encoding="utf-8") as f:
            print("\n--- Contents of myfile.txt ---")
            print(f.read(), end="")
            print("\n------------------------------")
    except FileNotFoundError:
        print(f"Error: {filename} not found. Create it first.")
    except OSError as e:
        print(f"Error: could not read {filename}: {e}")

def count_lines_in_file():
    """Ask for a filename and print the number of lines."""
    filename = input("Enter a filename: ").strip()
    try:
        count = 0
        with open(filename, "r", encoding="utf-8") as f:
            for _ in f:
                count += 1
        print(f"Line count for '{filename}': {count}")
    except FileNotFoundError:
        print(f"Error: {filename} not found.")
    except OSError as e:
        print(f"Error: could not read {filename}: {e}")

def count_four_letter_words():
    """Ask for a filename, then count exactly 4-letter words (case-insensitive)."""
    filename = input("Enter a filename: ").strip()
    try:
        with open(filename, "r", encoding="utf-8") as f:
            text = f.read()
        total = 0
        for piece in text.split():
            cleaned = "".join(ch for ch in piece if ch.isalpha())
            if len(cleaned) == 4:
                total += 1
        print(f"4-letter word count in '{filename}': {total}")
    except FileNotFoundError:
        print(f"Error: {filename} not found.")
    except OSError as e:
        print(f"Error: could not read {filename}: {e}")

def average_of_integers():
    """Ask for a filename, skip invalid lines, and print the average of integers."""
    filename = input("Enter a filename with integers (one per line): ").strip()
    try:
        values = []
        with open(filename, "r", encoding="utf-8") as f:
            for line in f:
                s = line.strip()
                if s == "":
                    continue
                try:
                    values.append(int(s))
                except ValueError:
                    # Ignore lines that are not integers
                    pass
        if len(values) == 0:
            print("No valid integers found.")
        else:
            avg = sum(values) / len(values)
            print(f"Average: {avg:.4f} (from {len(values)} numbers)")
    except FileNotFoundError:
        print(f"Error: {filename} not found.")
    except OSError as e:
        print(f"Error: could not read {filename}: {e}")

def list_directory():
    """List files and folders in the current directory (.)"""
    print("\n--- Directory listing (.) ---")
    try:
        items = os.listdir(".")
        items.sort(key=lambda x: x.lower())
        for name in items:
            print(name)
    except OSError as e:
        print(f"Error: could not list directory: {e}")
    print("----------------------------")

def show_if_exists():
    """Ask for a filename and print it if it exists; otherwise show an error."""
    filename = input("Enter a filename: ").strip()
    if os.path.exists(filename) and os.path.isfile(filename):
        try:
            with open(filename, "r", encoding="utf-8") as f:
                print(f"\n--- Contents of {filename} ---")
                print(f.read(), end="")
                print("\n-------------------------------")
        except OSError as e:
            print(f"Error: could not read {filename}: {e}")
    else:
        print(f"Error: {filename} not found.")

# Task 7: Search for a word in a file
def search_word_in_file():
    """Ask for filename and word, count occurrences and list line numbers."""
    filename = input("Enter a filename: ").strip()
    word = input("Enter a word to search: ").strip()
    # clean the search word - keep only letters and make lowercase
    target = ""
    for ch in word:
        if ch.isalpha():
            target = target + ch.lower()
    if target == "":
        print("Error: please enter a word with letters.")
        return
    try:
        count = 0
        line_numbers = []
        with open(filename, "r", encoding="utf-8") as f:
            line_num = 1
            for line in f:
                found_in_this_line = False
                for piece in line.split():
                    cleaned = ""
                    for ch in piece:
                        if ch.isalpha():
                            cleaned = cleaned + ch.lower()
                    if cleaned == target:
                        count = count + 1
                        found_in_this_line = True
                if found_in_this_line == True:
                    line_numbers.append(line_num)
                line_num = line_num + 1
        print(f"Word '{target}' appears {count} time(s) in '{filename}'.")
        if len(line_numbers) > 0:
            print("Found on line(s):", end=" ")
            for i in range(len(line_numbers)):
                if i == len(line_numbers) - 1:
                    print(line_numbers[i])
                else:
                    print(line_numbers[i], end=", ")
        else:
            print("No matching lines found.")
    except FileNotFoundError:
        print(f"Error: {filename} not found.")
    except OSError as e:
        print(f"Error: could not read {filename}: {e}")

# Task 8: Append a line to a file
def append_line_to_file():
    """Ask for filename and text, then append text to file."""
    filename = input("Enter a filename: ").strip()
    text = input("Enter line to append: ")
    if filename == "":
        print("Error: filename cannot be empty.")
        return
    try:
        # 'a' will create the file if it does not exist
        with open(filename, "a", encoding="utf-8") as f:
            f.write(text + "\n")
        print(f"Successfully appended to '{filename}'.")
    except OSError as e:
        print(f"Error: could not write to {filename}: {e}")

# Task 9: Show file info
def show_file_info():
    """Ask for filename and show size and last modified time."""
    filename = input("Enter a filename: ").strip()
    if filename == "":
        print("Error: filename cannot be empty.")
        return
    if os.path.exists(filename) and os.path.isfile(filename):
        try:
            size = os.path.getsize(filename)
            mtime = os.path.getmtime(filename)
            mod_time = datetime.datetime.fromtimestamp(mtime)
            mod_time_str = mod_time.strftime("%Y-%m-%d %H:%M:%S")
            print(f"\n--- File Info: {filename} ---")
            print(f"Size: {size} bytes")
            print(f"Last modified: {mod_time_str}")
            print("-------------------------------")
        except OSError as e:
            print(f"Error: could not get info for {filename}: {e}")
    else:
        print(f"Error: {filename} not found.")

def menu():
    print("""
==============================
Lab 1 - Python (Beginner)
==============================
1) Display myfile.txt
2) Count lines in a file
3) Count 4-letter words in a file
4) Average of integers from a file
5) List current directory
6) Show file if it exists
7) Search for a word in a file
8) Append a line to a file
9) Show file info
0) Quit
""")

def main():
    while True:
        menu()
        choice = input("Choose an option (0-9): ").strip()
        if choice == "1":
            display_myfile()
        elif choice == "2":
            count_lines_in_file()
        elif choice == "3":
            count_four_letter_words()
        elif choice == "4":
            average_of_integers()
        elif choice == "5":
            list_directory()
        elif choice == "6":
            show_if_exists()
        elif choice == "7":
            search_word_in_file()
        elif choice == "8":
            append_line_to_file()
        elif choice == "9":
            show_file_info()
        elif choice == "0":
            print("Goodbye!")
            break
        else:
            print("Invalid choice. Please enter a number from 0 to 9.")
        input("\nPress Enter to continue...")

if __name__ == "__main__":
    main()
← Back to timeline