Skip to content

Latest commit

 

History

History
223 lines (143 loc) · 4.64 KB

2.1.md

File metadata and controls

223 lines (143 loc) · 4.64 KB

Praca z plikami / Working with Files


Why it matters / Dlaczego to ważne

Files let programs save and load data — config files, user data, logs.

Pliki pozwalają programom zapisywać i wczytywać dane — pliki konfiguracyjne, dane użytkowników, logi.

Without files, all data disappears when program ends.

Bez plików wszystkie dane znikają gdy program się kończy.

Context managers (with statement) automatically close files even if errors occur — like a self-closing door.

Menedżery kontekstu (instrukcja with) automatycznie zamykają pliki nawet jeśli wystąpią błędy — jak drzwi samozamykające się.


Reading and writing / Czytanie i pisanie

Documentation:

Python Tutorial — Reading and Writing Files

Video:

Corey Schafer — Python File Objects (0:00–15:00)


Create sample.txt:

Utwórz sample.txt:

Hello, World!
This is line 2.
Python is awesome!

Create file_basics.py:

Utwórz file_basics.py:

# Read file / Czytaj plik
with open("sample.txt", "r") as file:
    content = file.read()
    print(content)

# Write file / Pisz plik
with open("output.txt", "w") as file:
    file.write("Line 1\n")
    file.write("Line 2\n")

# Append to file / Dopisz do pliku
with open("output.txt", "a") as file:
    file.write("Line 3\n")

Run:

Uruchom:

uv run python file_basics.py

File modes / Tryby:

  • "r" — read (default) / czytanie (domyślny)
  • "w" — write (overwrites) / pisanie (nadpisuje)
  • "a" — append / dopisywanie

Modern way: pathlib / Nowoczesny sposób: pathlib

The pathlib module is cleaner than string paths.

Moduł pathlib jest czystszy niż ścieżki stringowe.

Create pathlib_demo.py:

Utwórz pathlib_demo.py:

from pathlib import Path

# Write / Pisz
file = Path("config.txt")
file.write_text("Setting 1\nSetting 2\n")

# Read / Czytaj
content = file.read_text()
print(content)

# Check if exists / Sprawdź czy istnieje
if file.exists():
    print(f"Size: {file.stat().st_size} bytes")

# List files / Wylistuj pliki
for txt_file in Path(".").glob("*.txt"):
    print(f"Found: {txt_file.name}")

Run:

Uruchom:

uv run python pathlib_demo.py

Real-world example: config file / Przykład z życia: plik konfiguracyjny

This is how I handle config files in my projects.

Tak obsługuję pliki konfiguracyjne w moich projektach.

Create config_manager.py:

Utwórz config_manager.py:

from pathlib import Path

class ConfigManager:
    def __init__(self, config_file: str = "app.config"):
        self.config_file = Path(config_file)

    def save(self, settings: dict[str, str]) -> None:
        lines = [f"{key}={value}\n" for key, value in settings.items()]
        self.config_file.write_text("".join(lines))

    def load(self) -> dict[str, str]:
        if not self.config_file.exists():
            return {}

        config = {}
        for line in self.config_file.read_text().split("\n"):
            if "=" in line:
                key, value = line.split("=", 1)
                config[key] = value
        return config

# Usage / Użycie
config = ConfigManager()

# Save settings / Zapisz ustawienia
config.save({"theme": "dark", "language": "pl"})

# Load settings / Wczytaj ustawienia
settings = config.load()
print(f"Theme: {settings.get('theme')}")
print(f"Language: {settings.get('language')}")

Run:

Uruchom:

uv run python config_manager.py

Handle errors / Obsługa błędów

Always handle file errors gracefully.

Zawsze obsługuj błędy plików elegancko.

from pathlib import Path

def safe_read(filepath: str) -> str | None:
    try:
        return Path(filepath).read_text()
    except FileNotFoundError:
        print(f"File {filepath} not found")
        return None
    except PermissionError:
        print(f"No permission to read {filepath}")
        return None

content = safe_read("sample.txt")
if content:
    print(f"Read {len(content)} characters")

Podsumowanie / Summary

After this section you can:

Po tej sekcji potrafisz:

  • read and write files with open() and with

    czytać i pisać pliki z open() i with

  • use pathlib for modern file handling

    używać pathlib do nowoczesnej obsługi plików

  • handle file errors gracefully

    obsługiwać błędy plików elegancko

  • build real-world file-based tools

    budować narzędzia oparte na plikach z życia wziętych


Next: 2.2 — JSON i CSV