Data Science · मराठी आवृत्ती · Python basics
P9.2 Python मध्ये Text Files कशा वाचायच्या आणि लिहायच्या?
हे का शिकायचं?
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" विसरू नका.
उदाहरणं: copy करा आणि चालवा
उदाहरण A: छोटा log लिहा
हा code चालवा:
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:
Saved
याचा अर्थ: "w" mode ने नवीन file तयार झाली.
उदाहरण B: Line by line वाचा
हा code चालवा:
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:
T1 login issue
T2 refund request
T3 address change
Lines: 3
याचा अर्थ: Loop ने एक-एक line वाचली. strip() ने शेवटचा newline काढला.
उदाहरण C: नवीन line append करा
हा code चालवा:
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:
T1 login issue
T4 card blocked
याचा अर्थ: "a" mode ने जुना text न पुसता line जोडली.