Skip to content

7-dars: File I/O

Dars

Davomiyligi: 90 daqiqa Maqsad: Python'da fayl ochish, o'qish, yozish, JSON, CSV.

1. Fayl ochish — open()

python
f = open("data.txt", "r")
# ishlash...
f.close()

Rejimlar:

ModeVazifa
"r"Read (default)
"w"Write (ustiga)
"a"Append
"r+"Read + write
"b"Binary ("rb", "wb")
"x"Exclusive (yangi, mavjud bo'lsa xato)

2. with statement (eng yaxshi)

python
with open("data.txt", "r") as f:
    content = f.read()
# avtomatik close

Doim with ishlatish — fayl avtomatik yopiladi.

3. O'qish

python
# To'liq fayl
with open("data.txt") as f:
    text = f.read()
    print(text)

# Qator-qator
with open("data.txt") as f:
    for line in f:
        print(line, end="")

# Hammasini list ga
with open("data.txt") as f:
    lines = f.readlines()  # ['line1\n', 'line2\n', ...]

4. Yozish

python
with open("output.txt", "w") as f:
    f.write("Salom dunyo!\n")
    f.write("Ikkinchi qator\n")

"w" — fayl mavjud bo'lsa o'chiriladi.

Append

python
with open("log.txt", "a") as f:
    f.write(f"Log: {time.time()}\n")

5. Misol: Talabalar yozish/o'qish

Yozish

python
students = [
    ("Akmal", 22, 85.5),
    ("Aziza", 19, 92.0),
    ("Botir", 25, 78.5)
]

with open("students.txt", "w") as f:
    for name, age, score in students:
        f.write(f"{name},{age},{score}\n")

O'qish

python
students = []
with open("students.txt") as f:
    for line in f:
        parts = line.strip().split(",")
        name = parts[0]
        age = int(parts[1])
        score = float(parts[2])
        students.append((name, age, score))

for s in students:
    print(s)

6. JSON — eng yaxshi format

JSON (JavaScript Object Notation) — yengil, universal format.

python
import json

data = {
    "name": "Akmal",
    "age": 22,
    "scores": [85, 92, 78],
    "address": {
        "city": "Toshkent",
        "country": "O'zbekiston"
    }
}

# Yozish
with open("data.json", "w") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

# O'qish
with open("data.json") as f:
    loaded = json.load(f)

print(loaded["name"])         # Akmal
print(loaded["address"]["city"])  # Toshkent

JSON fayl:

json
{
  "name": "Akmal",
  "age": 22,
  "scores": [85, 92, 78],
  "address": {
    "city": "Toshkent",
    "country": "O'zbekiston"
  }
}

JSON

JSON — eng keng tarqalgan data format:

  • Web API
  • Sozlamalar fayli
  • Ma'lumot saqlash
  • Dasturlar orasida almashish

7. JSON string

python
import json

data = {"name": "Akmal", "age": 22}

# Dict → JSON string
s = json.dumps(data)
print(s)   # '{"name": "Akmal", "age": 22}'

# JSON string → dict
d = json.loads(s)
print(d["name"])

8. CSV — Excel format

python
import csv

# Yozish
with open("students.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Ism", "Yosh", "Ball"])  # header
    writer.writerow(["Akmal", 22, 85.5])
    writer.writerow(["Aziza", 19, 92.0])

# O'qish
with open("students.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Dict bilan

python
import csv

data = [
    {"name": "Akmal", "age": 22, "score": 85.5},
    {"name": "Aziza", "age": 19, "score": 92.0}
]

# Yozish
with open("students.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age", "score"])
    writer.writeheader()
    writer.writerows(data)

# O'qish
with open("students.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)

9. Path va Directory

python
import os

os.path.exists("data.txt")     # True/False
os.path.isfile("data.txt")     # fayl?
os.path.isdir("folder")        # papka?
os.path.getsize("data.txt")    # byte

# Hozirgi katalog
os.getcwd()

# Katalog yaratish
os.mkdir("new_folder")
os.makedirs("a/b/c")  # recursive

# Fayllarni ro'yxatga olish
for filename in os.listdir("."):
    print(filename)

# O'chirish
os.remove("file.txt")
os.rmdir("empty_folder")

10. pathlib (zamonaviy)

python
from pathlib import Path

p = Path("data.txt")

p.exists()           # True/False
p.is_file()
p.is_dir()
p.suffix             # '.txt'
p.stem               # 'data'
p.name               # 'data.txt'
p.parent             # papka

# O'qish
text = p.read_text()

# Yozish
p.write_text("Yangi matn")

# Iteratsiya
for f in Path(".").iterdir():
    print(f)

# Glob — naqsh bilan
for f in Path(".").glob("*.txt"):
    print(f)

pathlibzamonaviy yondashuv. os.path o'rniga shu.

11. Misol: Log file

python
from datetime import datetime

def log(message):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open("app.log", "a") as f:
        f.write(f"[{timestamp}] {message}\n")

log("Dastur ishga tushdi")
log("Foydalanuvchi kirdi")
log("Operatsiya bajarildi")

12. Misol: To-do list (file persistence)

python
import json

TASKS_FILE = "tasks.json"

def load_tasks():
    try:
        with open(TASKS_FILE) as f:
            return json.load(f)
    except FileNotFoundError:
        return []

def save_tasks(tasks):
    with open(TASKS_FILE, "w") as f:
        json.dump(tasks, f, indent=2, ensure_ascii=False)

def add_task(tasks, title):
    tasks.append({"title": title, "done": False})
    save_tasks(tasks)

def show_tasks(tasks):
    for i, t in enumerate(tasks, 1):
        status = "✓" if t["done"] else " "
        print(f"{i}. [{status}] {t['title']}")

def mark_done(tasks, idx):
    if 0 < idx <= len(tasks):
        tasks[idx - 1]["done"] = True
        save_tasks(tasks)

# Asosiy
tasks = load_tasks()
add_task(tasks, "Python o'rganish")
add_task(tasks, "Loyiha qilish")
mark_done(tasks, 1)
show_tasks(tasks)

13. Exception handling — try/except

python
try:
    with open("yoq.txt") as f:
        content = f.read()
except FileNotFoundError:
    print("Fayl yo'q!")
except PermissionError:
    print("Ruxsat yo'q")
except Exception as e:
    print(f"Boshqa xato: {e}")

C'da xato — manual tekshirish. Python — exception.

14. Common pitfalls

1. close() unutish

python
f = open("data.txt")
content = f.read()
# close yo'q — fayl ochiq qoladi

Yechim: with ishlatish.

2. Encoding

python
with open("data.txt", encoding="utf-8") as f:
    pass

Mac/Linux'da UTF-8 default. Windows — har xil.

Doim encoding="utf-8".

3. JSON va o'zbek

python
json.dump(data, f, ensure_ascii=False)  # O'zbek harflar to'g'ri

ensure_ascii=False — Unicode harflarni to'g'ri saqlaydi.

Topshiriqlar

1 — Birinchi fayl

first_file.py:

python
# Yozish
with open("hello.txt", "w") as f:
    f.write("Salom dunyo!\n")
    f.write("Bu mening Python faylim.\n")

# O'qish
with open("hello.txt") as f:
    print(f.read())

2 — Talabalar TXT

students_txt.py:

10 ta talaba ma'lumotini students.txt'ga yozing, keyin o'qib chiqib statistika.

3 — JSON

json_demo.py:

python
import json

book = {
    "title": "Python Programming",
    "author": "John Doe",
    "year": 2024,
    "chapters": ["Intro", "Basics", "Advanced"]
}

with open("book.json", "w") as f:
    json.dump(book, f, indent=2)

with open("book.json") as f:
    loaded = json.load(f)

print(loaded["title"])

4 — CSV

csv_demo.py — 5 ta talaba CSV'ga.

Excel'da ochib ko'ring.

5 — Log

logger.py — Dars matnidagi log dasturi.

6 — To-do

todo.py — JSON file persistence bilan to-do app.

CRUD: add, show, mark done, delete.

7 — Word count tool

wc.py:

python
import sys

if len(sys.argv) != 2:
    print("Foydalanish: python wc.py <fayl>")
    sys.exit(1)

filename = sys.argv[1]

with open(filename) as f:
    text = f.read()

print(f"Belgilar: {len(text)}")
print(f"So'zlar: {len(text.split())}")
print(f"Qatorlar: {text.count(chr(10))}")

Sinab ko'ring: python wc.py students.txt

8 — File copy

copy.py:

python
import sys

with open(sys.argv[1]) as src:
    content = src.read()

with open(sys.argv[2], "w") as dst:
    dst.write(content)

print("Nusxalandi")

9 — Directory listing

ls.py:

python
from pathlib import Path

for f in Path(".").iterdir():
    if f.is_file():
        size = f.stat().st_size
        print(f"{f.name:30} {size:>10} byte")

10 — GitHub

bash
$ mkdir 6-oy-dars-7
$ git add . && git commit -m "feat: dars 7 - file I/O" && git push

Lug'at

TerminIzoh
open()Fayl ochish
withAvtomatik close
read / writeO'qish / yozish
readlinesList olish
jsonJSON format
csvExcel format
pathlibZamonaviy fayl yo'l
try/exceptException handling
FileNotFoundErrorFayl yo'q xato
encodingUTF-8 va h.k.

Keyingi dars

8-dars: OOP (class) →

Master IT o'quv markazi — o'qitish rejasi