לדלג לתוכן

6.4 pathlib הרצאה

מודול pathlib

  • התקן: pip install pathlib
  • מודול שמאפשר לנו לגשת לקבצים במחשב בצורה פשוטה ונוחה

  • יצירת אובייקט Path - מסמל נתיב במחשב

    from pathlib import Path
    
    # Specify path of the file
    file_path = Path(r"C:\Users\amitp\file.txt")
    file_path = Path(".\file.txt")
    file_path = Path("file.txt")
    file_path = Path("C:\Users") / "amitp" / "file.txt"
    

  • בדיקה האם הנתיב הזה קיים:

    # Checking if file exist
    if file_path.exists():
        print("File exists.")
    else:
        print("File does not exist.")
    

  • כתיבת טקסט לקובץ

    # Writing to a file
    file_path.write_text("Hello, pathlib!")
    

  • קריאה מקובץ

    # Reading from a file
    content = file_path.read_text()
    print("File Content:", content)
    

  • קבל כל מיני תכונות על הקובץ

    # File attributes
    print("File Name:", file_path.name)
    print("Parent Directory:", file_path.parent)
    print("File Extension:", file_path.suffix)
    

  • יצירת תקייה חדשה:

    # Creating new directory
    new_directory = Path('new_folder')
    new_directory.mkdir()
    print("Directory created:", new_directory)
    

  • לעבור על כל הקבצים בתקייה:

    # Using glob
    matching_files = directory_path.glob('*')
    print("Matching Files:", list(matching_files))