|12. File Handling in Python
Chapter 12Python Tutorial~1 min read

File Handling in Python

Files read/write करणे

File handling म्हणजे Python program मधून files open, read, write, close करणे. Programs बंद झाल्यावरही data टिकवायला files वापरतात.

File Modes

  • "r" — Read mode (default) — file वाचायला. File नसेल तर error.
  • "w" — Write mode — file मध्ये लिहायला. नसेल तर नवी बनवतो. असेल तर overwrite!
  • "a" — Append mode — शेवटी add करतो. नसेल तर नवी बनवतो.
  • "x" — Create mode — नवी file बनवतो. आधीच असेल तर error.
  • "rb" / "wb" — Binary mode — images, PDFs साठी

File write करणे

python
# Write mode — file बनवणे/overwrite करणे
file = open("notes.txt", "w")
file.write("नमस्कार!\n")
file.write("हे माझे Python notes आहेत.\n")
file.close()  # file close करणे important!

# Append mode — existing file मध्ये add करणे
file = open("notes.txt", "a")
file.write("आज loops शिकलो.\n")
file.close()

File Read करणे

File read करणे

python
# Read mode
file = open("notes.txt", "r")
content = file.read()    # सगळा content एकत्र
print(content)
file.close()

# Line by line वाचणे
file = open("notes.txt", "r")
for line in file:
    print(line.strip())  # .strip() — trailing \n काढतो
file.close()

# readline() — एक line
file = open("notes.txt", "r")
first_line = file.readline()
print(first_line)
file.close()

with Statement — Best Practice

with open() — auto close होतो!

python
# with statement — automatically file close करतो
# file.close() विसरायची गरज नाही!

# Writing
with open("data.txt", "w") as f:
    f.write("Python File Handling\n")
    f.write("with statement best practice आहे!\n")

# Reading
with open("data.txt", "r") as f:
    content = f.read()
    print(content)

# Lines as list
with open("data.txt", "r") as f:
    lines = f.readlines()
    print(lines)  # ['Python File Handling\n', ...]
💡

with open() as f: हे नेहमी वापरा! file.close() विसरायचा धोका नाही. Error आला तरी file automatically close होते.

Key Points — लक्षात ठेवा

  • open(filename, mode) — file उघडतो
  • "r" read, "w" write (overwrite), "a" append, "x" create
  • .read() — सगळे, .readline() — एक line, .readlines() — list
  • .write(text) — text लिहितो
  • with open() as f: — best practice, auto-close
0/12 chapters पूर्ण