ლექცია 09 · IX კვირაLecture 09 · Week IX
ფაილებთან
მუშაობაWorking with
files
ფაილიდან კითხვა · ფაილში ჩაწერა · მანიპულირების ფუნქციები Reading from files · writing to files · file operations
დღეს ასევე: შუალედური გამოცდის შედეგების განხილვა Also today: going over the midterm results
მოტივაციაMotivation
რატომ გვჭირდება ფაილებიWhy we need files
პროგრამის დასრულებისას ყველა ცვლადი ქრება. ფაილი — ერთადერთი გზა, მონაცემი „გადარჩეს“.
When a program ends, every variable disappears. A file is the only way for data to survive.
შენახვაSaving
მომხმარებლის პარამეტრები, თამაშის ანგარიში, პროგრესი
User settings, game scores, progress
შეტანაInput
დიდი მოცულობის მონაცემი, რომლის ხელით აკრეფაც აზრს მოკლებულია
Large volumes of data that would be pointless to type by hand
გაცვლაExchange
CSV, JSON, ლოგები — სხვა პროგრამებთან კომუნიკაცია
CSV, JSON, logs — talking to other programs
ანგარიშიReports
გამოთვლის შედეგის ჩაწერა, რომ ეკრანზე არ დაიკარგოს
Writing results down so they are not lost on screen
with ავტომატურად აკეთებს.
Three steps, always1) open → 2) read or write → 3) close. In Python, with takes care of the third step for you.
საფუძველიFundamentals
open() და რეჟიმებიopen() and its modes
f = open("data.txt", "r", encoding="utf-8")
# file mode encoding
| რეჟიმიMode | დასახელებაName | ქცევაBehaviour |
|---|---|---|
"r" | read — კითხვაread | ნაგულისხმევი. თუ ფაილი არ არსებობს → FileNotFoundError
The default. If the file does not exist → FileNotFoundError |
"w" | write — ჩაწერაwrite | შიგთავსს შლის! არარსებობისას ქმნის ახალს Erases the contents! Creates the file if it is missing |
"a" | append — დამატებაappend | წერს ბოლოში, არსებულს ინახავს Writes at the end, keeping what is there |
"x" | exclusive — შექმნაexclusive create | თუ ფაილი უკვე არსებობს → შეცდომა Errors if the file already exists |
"r+" | კითხვა + ჩაწერაread + write | ორივე ერთდროულადBoth at once |
"rb" "wb" | ბინარულიbinary | სურათები, არქივები — ტექსტად არ იკითხება Images, archives — not readable as text |
"w" რეჟიმი ფაილს მაშინვე ასუფთავებს, ჩაწერამდეც კი. შემთხვევით "a"-ს ნაცვლად "w" რომ დაწერო — მონაცემები წაიშლება.
The most expensive mistakeMode "w" empties the file immediately, before you write anything. Type "w" where you meant "a" and the data is gone.
სწორი სტილიGood style
with ... as — კონტექსტის მენეჯერიwith ... as — the context manager
ხელითBy hand
f = open("data.txt", "r", encoding="utf-8")
content = f.read()
f.close() # what if you forget?
# what if it fails halfway?
with-ითWith with
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
# the file is already closed here — automatically
print(content)
with-ით ვმუშაობთ. ის ფაილს ხურავს მაშინაც კი, თუ ბლოკის შიგნით შეცდომა მოხდა.
RuleAlways use with for files. It closes the file even if an error occurs inside the block.
with ... as ინსტრუქციას სიღრმისეულად XII კვირაზე დავუბრუნდებით — ის შეცდომების დამუშავებასთანაა დაკავშირებული.
We return to with ... as in depth in week XII — it belongs with error handling.
კრიტიკული დეტალიA critical detail
encoding="utf-8" — ქართულისთვის სავალდებულოencoding="utf-8" — mandatory for non-ASCII text
# ⚠ on Windows the default encoding is not UTF-8
with open("names.txt", "r") as f: # risky!
print(f.read())
# UnicodeDecodeError, or boxes instead of letters
# ✓ always state it
with open("names.txt", "r", encoding="utf-8") as f:
print(f.read())
encoding="utf-8" — კითხვისასაც და ჩაწერისასაც.
RuleAlways write encoding="utf-8" for text files — both when reading and when writing.
კითხვაReading
ოთხი გზა წასაკითხადFour ways to read
ნინო 92
გიორგი 78
ანა 85
with open("students.txt", encoding="utf-8") as f:
text = f.read() # everything as one string
print(text)
with open("students.txt", encoding="utf-8") as f:
line = f.readline() # a single line
print(line) # "ნინო 92\n"
with open("students.txt", encoding="utf-8") as f:
lines = f.readlines() # a list of lines
print(lines) # ['ნინო 92\n', 'გიორგი 78\n', ...]
# ✓ the best way — loop over the file directly
with open("students.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())
ჩაწერაWriting
ფაილში ჩაწერაWriting to a file
# "w" — from scratch (the old contents are erased)
with open("output.txt", "w", encoding="utf-8") as f:
f.write("პირველი ხაზი\n") # the \n is yours to add!
f.write("მეორე ხაზი\n")
# "a" — append at the end
with open("output.txt", "a", encoding="utf-8") as f:
f.write("მესამე ხაზი\n")
# several lines at once
lines = ["ერთი\n", "ორი\n", "სამი\n"]
with open("output.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
# print() straight into a file
with open("report.txt", "w", encoding="utf-8") as f:
print("ანგარიში", file=f)
print(f"ჯამი: {100:.2f}", file=f)
write() ხაზს არ წყვეტსprint()-ისგან განსხვავებით, \n ხელით უნდა დაწერო.
write() adds no line breakUnlike print(), you must write the \n yourself.
ფაილის გზაFile paths
სად ეძებს Python ფაილსWhere Python looks for a file
# a relative path — from the current folder
open("data.txt")
open("files/data.txt")
open("../data.txt") # one level up
# an absolute path
open(r"C:\Users\K\data.txt") # r — a raw string!
open("C:/Users/K/data.txt") # or forward slashes
open("/home/user/data.txt") # Linux / macOS
"C:\Users\new"-ში \n ხაზის გადატანად წაიკითხება! გამოსავალი: r"C:\Users\new" ან "C:/Users/new".
The Windows trapIn "C:\Users\new" the \n is read as a newline! The fix: r"C:\Users\new" or "C:/Users/new".
from pathlib import Path
p = Path("data") / "students.txt" # OS-independent
print(p.exists())
print(p.suffix) # .txt
text = p.read_text(encoding="utf-8") # one line!
p.write_text("ახალი შიგთავსი", encoding="utf-8")
მანიპულირებაFile operations
ფაილებზე ოპერაციებიOperating on files
import os
print(os.path.exists("data.txt")) # does it exist?
print(os.path.getsize("data.txt")) # size in bytes
print(os.path.abspath("data.txt")) # the full path
print(os.path.basename("a/b/c.txt")) # c.txt
print(os.path.splitext("c.txt")) # ('c', '.txt')
os.rename("old.txt", "new.txt") # rename
os.remove("temp.txt") # delete — irreversible!
os.mkdir("reports") # create a folder
print(os.listdir(".")) # what is in the folder
if os.path.exists("data.txt"):
with open("data.txt", encoding="utf-8") as f:
print(f.read())
else:
print("ფაილი ვერ მოიძებნა")პრაქტიკაPractice
ტექსტური მონაცემების დამუშავებაProcessing text data
ნინო,92
გიორგი,78
ანა,85
ლევანი,61
total = 0
count = 0
best_name = ""
best_score = -1
with open("grades.txt", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line: # skip blank lines
continue
name, score = line.split(",")
score = int(score)
total += score
count += 1
if score > best_score:
best_score = score
best_name = name
print(f"სტუდენტი: {count}")
print(f"საშუალო: {total / count:.2f}")
print(f"საუკეთესო: {best_name} ({best_score})")
strip → split → convert → accumulate — ფაილებთან მუშაობის საფუძველია. სტუდენტებმა ის ზეპირად უნდა იცოდნენ.
This pattern — strip → split → convert → accumulate — is the backbone of file processing. They should know it by heart.
სრული მაგალითიFull example
ჩანაწერების დამატება და ანგარიშის შექმნაAdding records and producing a report
FILE = "grades.txt"
def add_record():
name = input("სახელი: ").strip()
score = input("ქულა: ").strip()
with open(FILE, "a", encoding="utf-8") as f:
f.write(f"{name},{score}\n")
print("ჩაწერილია ✓")
def show_report():
try:
with open(FILE, encoding="utf-8") as f:
rows = [line.strip().split(",") for line in f if line.strip()]
except FileNotFoundError:
print("ფაილი ჯერ არ არსებობს")
return
print(f"\n{'სახელი':<15}{'ქულა':>6}")
print("-" * 21)
for name, score in rows:
print(f"{name:<15}{score:>6}")
while True:
choice = input("\n1 დამატება · 2 ანგარიში · 0 გასვლა: ")
if choice == "0":
break
elif choice == "1":
add_record()
elif choice == "2":
show_report()
დიაგნოსტიკაTroubleshooting
ხშირი შეცდომებიCommon errors
| შეცდომაError | მიზეზი და გამოსავალიCause and fix |
|---|---|
FileNotFoundError |
ფაილი სხვა საქაღალდეშია. შეამოწმე os.getcwd(). VS Code-ში საქაღალდე გახსენი, არა ცალკე ფაილი
The file is in another folder. Check os.getcwd(). In VS Code open the folder, not a single file |
UnicodeDecodeError |
დაგავიწყდა encoding="utf-8"You forgot encoding="utf-8" |
| ფაილი დაცარიელდაThe file went empty | "w" გამოიყენე "a"-ს ნაცვლადYou used "w" where you meant "a" |
| ხაზები ერთმანეთს ეწებებაLines run together | f.write()-ს \n აკლიაThe \n is missing from f.write() |
| ხაზის ბოლოს ზედმეტი სიმბოლოA stray character at the line end | დაგავიწყდა line.strip()You forgot line.strip() |
ValueError: not enough values to unpack |
ცარიელი ხაზი ან არასწორი გამყოფი. დაამატე if not line: continue
A blank line or the wrong separator. Add if not line: continue |
| ფაილი „დაკავებულია“The file is “in use” | Excel-ში ან სხვა პროგრამაშია გახსნილიIt is open in Excel or another program |
შემაჯამებელიWrap-up
რა უნდა დაგამახსოვრდესWhat to remember
with open(path, mode, encoding="utf-8") as f:— ერთადერთი სწორი სტილი- რეჟიმები:
rკითხვა ·wშლის და წერს ·aამატებს ბოლოში - კითხვა:
read()·readlines()· უკეთესი —for line in f - ჩაწერა:
write()(\nხელით) ·print(..., file=f) - ქართული ტექსტი →
encoding="utf-8"ყოველთვის - დამუშავების შაბლონი:
strip → split → convert → accumulate
with open(path, mode, encoding="utf-8") as f:— the only correct style- Modes:
rread ·werases and writes ·aappends at the end - Reading:
read()·readlines()· better still —for line in f - Writing:
write()(add\nyourself) ·print(..., file=f) - Non-ASCII text → always
encoding="utf-8" - The processing pattern:
strip → split → convert → accumulate
datetime).
At home1) Write 20 random numbers to a file, then read them back and find the sum, average and maximum. 2) Merge two files into a third. 3) Count the words in a text file. 4) A logger that appends the date on every run (datetime).
tuple.
Next — lecture 10Lists: creating, modifying, sorting, multidimensional lists, and tuple.