לדלג לתוכן

6.3 מודולים מובנים שימושיים הרצאה

  • בהרצאה הקרובה נראה כמה מודולים מובנים בפייתון שמאפשרים לנו לעשות דברים מאוד שימושים.

מודול string

import string
print(string.ascii_letters)
print(string.digits)
print(string.punctuation)

- במודול מוגדרים מספר משתנים שמכילים רשימות של סוגים של אותיות

מודול time

  • הפונקציה time.time מביאה לנו את כמות השניות שעברו מ1970.1.1, המספר הזה נקרא גם unix timestamp

    import time
    
    current_time_seconds = time.time()
    print("Current Time in Seconds:", current_time_seconds)
    

    למה צריך פונקציה כזאת? כל המחשבים בעולם ככלל משתמשים בשיטה הזו כדי לשמור זמן (כדי לשמור על אחידות), בסוף יש פונקציות שאחראיות להמיר בין המספר הזה לתאריך קריא. כך שאל תדאגו, אתם לא צריכים לחשב בעצמכם מה המספר הזה אומר.

  • הפונקציה time.sleep עוצר את הריצה של התוכנה למשך כמות השניות שציינו

    import time
    
    print("Before Pause")
    time.sleep(2)  # Pauses execution for 2 seconds
    print("After Pause")
    

מודול datetime

  • מביא לנו את התאריך המדוייק
    from datetime import datetime
    
    current_datetime = datetime.now()
    print("Current Date and Time:", current_datetime)
    
  • במודול יש המון פונקציליות שקשורה לתאריכים, המון פעולות שאפשר לעשות על תאריכים, דרכים שונות להדפיס תאריכים ועוד.

מודול os

  • מודול שמאפשר לנו לגשת ולעשות פעולות שקשורת למערכת הפעלה
    import os
    
    current_directory = os.getcwd()
    print(f"Current Directory: {current_directory}")
    
    files_in_directory = os.listdir(current_directory)
    print(f"Files in Directory: {files_in_directory}")
    
    new_directory = "example_directory"
    os.mkdir(new_directory)
    print(f"Directory '{new_directory}' created.")
    
    os.system("dir")
    
    if os.path.exists(path_to_check):
        print(f"Path '{path_to_check}' exists.")
    
  • הפונקציה os.getcwd - תחזיר לנו את הנתיב של התקייה שבה הקוד רץ
  • הפונקציה os.listdir - מקבלת נתיב של תקייה ואומרת איזה קבצים יש בה
  • הפונקציה os.mkdir - מקבלת נתיב ויוצרת תיקייה
  • הפונקציה os.system - מריצה פקודת טרמינל
  • הפונקציה os.path.exists - בודקת האם נתיב כלשהו קיים.