# P9.2 Python मध्ये Text Files कशा वाचायच्या आणि लिहायच्या?

Source: https://ravindrabagale.com/mr/datascience/py09-how-to-read-and-write-csv-json-and-text-files-in-python/p9-2-how-to-read-and-write-text-files-in-python.html
Language: mr (Marathi with English technical terms)

हे का शिकायचं?

Logs, notes आणि साधे reports text files मध्ये असतात.

हे काय आहे?

with open(path, mode, encoding="utf-8") as f: — "w" लिहिणं (जुनं पुसतं), "r" वाचणं, "a" शेवटी जोडणं. with file आपोआप बंद करतो.

कसं करायचं?

Step 1. with open(...) as f: लिहा.
Step 2. Mode निवडा: w, r किंवा a.
Step 3. encoding="utf-8" विसरू नका.

उदाहरण A: छोटा log लिहा

```python
with open("tickets.txt", "w", encoding="utf-8") as f:
    f.write("T1 login issue\n")
    f.write("T2 refund request\n")
    f.write("T3 address change\n")
print("Saved")
```

Output:

```text
Saved
```

याचा अर्थ: "w" mode ने नवीन file तयार झाली.

उदाहरण B: Line by line वाचा

```python
with open("tickets.txt", "w", encoding="utf-8") as f:
    f.write("T1 login issue\nT2 refund request\nT3 address change\n")
count = 0
with open("tickets.txt", encoding="utf-8") as f:
    for line in f:
        count += 1
        print(line.strip())
print("Lines:", count)
```

Output:

```text
T1 login issue
T2 refund request
T3 address change
Lines: 3
```

याचा अर्थ: Loop ने एक-एक line वाचली. strip() ने शेवटचा newline काढला.

उदाहरण C: नवीन line append करा

```python
with open("tickets.txt", "w", encoding="utf-8") as f:
    f.write("T1 login issue\n")
with open("tickets.txt", "a", encoding="utf-8") as f:
    f.write("T4 card blocked\n")
print(open("tickets.txt", encoding="utf-8").read())
```

Output:

```text
T1 login issue
T4 card blocked
```

याचा अर्थ: "a" mode ने जुना text न पुसता line जोडली.

रवींद्र बागले यांची tip

नेहमी `encoding="utf-8"` द्या. त्यामुळे ₹, €, £ आणि मराठी/हिंदी text प्रत्येक computer वर सुरक्षित राहतो.
