קריאה וכתיבה, with, נתיבים עם pathlib וקידוד UTF-8.
Reading and writing, with, paths with pathlib and UTF-8 encoding.
כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.
חימום: 3 שאלותWarm-up: 3 questions
תרגיליםExercises
תרגילExercise 1
שמירת רשימהSave a list
כתבו את שלושת הספרים ברשימה books לקובץ books.txt, ספר בשורה. אחר כך קראו את הקובץ והדפיסו כמה שורות יש בו.
Write the three books in books to books.txt, one per line. Then read the file back and print how many lines it has.
איך הפלט אמור להיראות?What should the output look like?
3
main.py
רמזHint 1:לולאה עם f.write(b + "\n").A loop with f.write(b + "\n").
רמזHint 2:len(f.readlines()) או לולאה.len(f.readlines()) or a loop.
כתבו log(pages) שמוסיפה לקובץ log.txt שורה read N pages (בלי למחוק את הקודם). קראו לה עם 40, 55 ו-20, ואז קראו את הקובץ והדפיסו את סך העמודים.
Write log(pages) that appends a line read N pages to log.txt (without erasing). Call it with 40, 55 and 20, then read the file and print the total pages.
איך הפלט אמור להיראות?What should the output look like?
בעזרת pathlib צרו תיקייה notes, וכתבו בה שלושה קבצים day1.txt עד day3.txt שכל אחד מכיל Day N. הדפיסו את שמות הקבצים בתיקייה ממוינים, ואת התוכן של day2.txt.
With pathlib create a folder notes and write three files day1.txt to day3.txt, each containing Day N. Print the sorted file names in the folder, then the content of day2.txt.
איך הפלט אמור להיראות?What should the output look like?
מדף, צעד 12: שמירה וטעינהShelf, step 12: save and load
פרויקט מלווהCompanion project
כתבו save(shelf, path) ששומרת כל ספר כשורה title|author, ו-load(path) שמחזירה רשימת מילונים (ורשימה ריקה אם הקובץ לא קיים). שמרו שני ספרים, טענו, והדפיסו את הכותרות.
Write save(shelf, path) storing each book as a line title|author, and load(path) returning a list of dicts (or an empty list if the file doesn't exist). Save two books, load them, and print the titles.
איך הפלט אמור להיראות?What should the output look like?
כתבו backup(path) שמעתיקה קובץ ל-<שם>.bak1, ואם קיים כבר אז ל-.bak2 וכן הלאה, ומחזירה את שם הגיבוי. צרו shelf.txt, גבו שלוש פעמים, והדפיסו את שמות הגיבויים.
Write backup(path) that copies a file to <name>.bak1, or .bak2 if that exists, and so on, returning the backup name. Create shelf.txt, back it up three times, and print the backup names.
איך הפלט אמור להיראות?What should the output look like?
shelf.txt.bak1
shelf.txt.bak2
shelf.txt.bak3
main.py
רמזHint 1:לולאה n = 1 עד שמוצאים שם פנוי.Loop from n = 1 until a free name is found.
רמזHint 2:Path(path).with_suffix(...) או f-string.Path(path).with_suffix(...) or an f-string.