Python File Handling म्हणजे काय? Read, Write, Append, CSV, JSON आणि Practical Project

रुपेश पवार

Table of Contents

Python मध्ये सुरुवात करताना आपण Variables, Data Types, Conditions, Loops आणि Functions शिकतो. हे concepts समजले की छोटे programs तयार करणं फार अवघड राहत नाही. पण इथून पुढे एक वेगळाच प्रश्न समोर येतो.

Program बंद केल्यानंतर आपला data कुठे राहणार?

समजा आपण एक छोटं Notes App तयार केलं. User ने त्यामध्ये: आज Python मध्ये File Handling शिकलो. उद्या CSV आणि JSON चा practice करायचा. असं लिहिलं.

हा data फक्त variable मध्ये ठेवला तर program बंद केल्यानंतर तो data पुन्हा मिळणार नाही. कारण variable मधला data program चालू असतानाच्या memory मध्ये असतो. पण हाच data एखाद्या file मध्ये save केला, तर program बंद झाल्यानंतरही तो उपलब्ध राहतो.

इथून File Handling ची गरज सुरू होते.

Software development मध्ये data कायमस्वरूपी ठेवण्याचे अनेक मार्ग आहेत. काही ठिकाणी simple text file पुरेशी असते, काही ठिकाणी CSV किंवा JSON उपयोगी पडतो, तर application मोठं झाल्यावर Database ची गरज पडते.

म्हणून File Handling शिकताना फक्त open() चा syntax पाठ करण्यापेक्षा कोणत्या परिस्थितीत कोणता file format आणि कोणता mode वापरायचा, हे समजून घेणं जास्त महत्त्वाचं आहे. या लेखात आपण तेच practical पद्धतीने पाहणार आहोत.

सोप्या भाषेत सांगायचं तर Python program मधून file तयार करणे, file मधला data वाचणे, नवीन data लिहिणे आणि existing data मध्ये नवीन माहिती add करणे म्हणजे File Handling.

उदाहरणार्थ:

File Typeसामान्य उपयोग
.txtSimple text किंवा notes
.csvRows आणि columns मधला data
.jsonStructured data
.jpg, .pngImages
.pdfDocuments

म्हणजे File Handling हा फक्त .txt file चा topic नाही. आपण कोणत्या प्रकारचा data हाताळतो यावर file format निवडला जातो.

हा फरक सुरुवातीलाच समजून घेतला तर File Handling खूप सोपं वाटतं.

name = “Rupesh” इथे name मध्ये data आहे. पण हा data program च्या memory मध्ये आहे. Program बंद झाला की हा variable पुन्हा उपलब्ध नसतो.

दुसरीकडे:

with open(“user.txt”, “w”, encoding=”utf-8″) as file:

    file.write(“Rupesh”)

इथे data file मध्ये save होतो.

म्हणून:

Variable → Program चालू असताना data

File → Program बंद झाल्यानंतरही ठेवता येणारा data

अर्थात, file हा database इतका powerful नसतो; पण छोट्या applications आणि simple data storage साठी तो पुरेसा असू शकतो.

File सोबत काम करण्यासाठी Python मध्ये open() function वापरता येतो.

file = open(“data.txt”, “r”)

इथे:

  • data.txt → file चे नाव
  • “r” → read mode
  • file → file object

File वापरून झाल्यावर ती close करण्यासाठी:

file.close()

असं करता येतं. पण practical code मध्ये मी शक्य असेल तिथे with open() वापरण्याला preference देतो. त्याबद्दल थोड्याच वेळात पाहू.

open() मधला mode Python ला सांगतो की file सोबत आपल्याला काय करायचं आहे.

Modeकाय करतो?लक्षात ठेवण्यासारखं
rReadFile असणे आवश्यक
wWriteजुना content overwrite होऊ शकतो
aAppendनवीन data शेवटी add होतो
xCreateFile आधीपासून असेल तर error
r+Read + WriteExisting file वर काम
w+Write + ReadExisting content overwrite होऊ शकतो
a+Append + Readशेवटी data add करण्यासाठी

Beginner असाल तर आधी r, w, a हे तीन modes पक्के करा.

समजा notes.txt मध्ये:

Python शिकत आहे. आज File Handling चा अभ्यास केला. आता Python मधून तो data वाचायचा आहे.

with open(“notes.txt”, “r”, encoding=”utf-8″) as file:

    data = file.read()

print(data)

Output:

Python शिकत आहे. आज File Handling चा अभ्यास केला. इथे read() पूर्ण file चा content वाचतो.

हा एक छोटासा पण practical प्रश्न आहे. जर file 2-3 lines ची असेल तर:

data = file.read()

अगदी ठीक. पण file खूप मोठी असेल तर पूर्ण content एकाच वेळी memory मध्ये घेणं योग्य नसेल.

अशावेळी line-by-line process करता येतो:

with open(“server.log”, “r”, encoding=”utf-8″) as file:

    for line in file:

        print(line.strip())

यातून एक महत्त्वाची developer habit शिकता येते:

Data किती आहे हे लक्षात घेऊन operation निवडा.

फक्त method माहित आहे म्हणून तो प्रत्येक ठिकाणी वापरायचा नसतो.

with open(“notes.txt”, “r”, encoding=”utf-8″) as file:

    first_line = file.readline()

print(first_line)

readline() एका वेळी एक line read करतो. पुन्हा call केल्यावर पुढची line मिळते.

with open(“notes.txt”, “r”, encoding=”utf-8″) as file:

    lines = file.readlines()

print(lines)

जर file मध्ये:

Python, Java, C++

असेल तर lines मध्ये प्रत्येक line चा data list म्हणून मिळतो.

[‘Python\n’, ‘Java\n’, ‘C++’]

for loop सोबत:

for line in lines:

    print(line.strip())

इथे strip() चा उपयोग शेवटी असलेला newline किंवा unwanted whitespace काढण्यासाठी केला आहे.

नवीन data लिहायचा असेल तर:

with open(“message.txt”, “w”, encoding=”utf-8″) as file:

    file.write(“Hello Python!”)

File नसेल तर ती तयार होऊ शकते. पण इथे beginner ने सर्वात जास्त काळजी घ्यायची आहे.

समजा message.txt मध्ये आधी:

Hello Python. Learning File Handling आहे.

आता:

with open(“message.txt”, “w”, encoding=”utf-8″) as file:

    file.write(“New Message”)

केलं तर जुना content replace होऊ शकतो. म्हणून production code मध्ये existing file वर w वापरताना हा प्रश्न स्वतःला विचारा:

“मला खरंच जुना data delete करून नवीन data लिहायचा आहे का?” जर उत्तर नाही असेल, तर कदाचित a किंवा दुसरा approach योग्य असेल.

समजा आपण application मध्ये logs save करत आहोत. प्रत्येक नवीन log साठी जुना log delete व्हायला नको.

with open(“app.log”, “a”, encoding=”utf-8″) as file:

    file.write(“User logged in\n”)

a म्हणजे append.

आधी:

Application Started

नंतर:

Application Started

User logged in असं होईल.

एक सोपा rule

r → वाचा

w → नवीन लिहा / overwrite होऊ शकतो

a → शेवटी add करा

हा rule सुरुवातीला लक्षात ठेवला तरी बरीच confusion कमी होते.

with open(“newfile.txt”, “x”, encoding=”utf-8″) as file:

    file.write(“First content”)

जर file आधीपासून असेल तर FileExistsError येऊ शकतो. म्हणून existing file accidentally overwrite होऊ नये अशा परिस्थितीत x उपयोगी पडू शकतो.

Manual approach:

file = open(“data.txt”, “r”)

data = file.read()

file.close()

यात close() लक्षात ठेवावं लागतं. with वापरल्यावर:

with open(“data.txt”, “r”, encoding=”utf-8″) as file:

    data = file.read()

code छोटा आणि readable राहतो आणि with block संपल्यानंतर file context व्यवस्थित बंद करण्याची व्यवस्था Python करते. म्हणून beginner code असो किंवा project code — with open() हा pattern लवकर शिकून घेणं फायदेशीर आहे.

Python मधून Marathi किंवा इतर Unicode text save करताना encoding लक्षात ठेवणं महत्त्वाचं आहे.

with open(“notes.txt”, “w”, encoding=”utf-8″) as file:

    file.write(“आज Python मध्ये File Handling शिकलो.”)

Read करताना:

with open(“notes.txt”, “r”, encoding=”utf-8″) as file:

    data = file.read()

print(data)

Local-language content, multilingual applications किंवा user-generated text असलेल्या projects मध्ये ही छोटी गोष्ट नंतर debugging वाचवू शकते.

एक string लिहायची असेल:

with open(“data.txt”, “w”, encoding=”utf-8″) as file:

    file.write(“Python”)

अनेक lines असतील:

lines = [

    “Python\n”,

    “Java\n”,

    “C++\n”

]

with open(“languages.txt”, “w”, encoding=”utf-8″) as file:

    file.writelines(lines)

इथे एक गोष्ट लक्षात ठेवा:

writelines() प्रत्येक item च्या शेवटी आपोआप \n लावत नाही.

म्हणून lines वेगळ्या हव्या असतील तर \n स्वतः द्यावा लागतो.

File read करणं हा फक्त पहिला step आहे. खरा फायदा तेव्हा होतो जेव्हा आपण read केलेल्या data वर processing करतो.

उदाहरण:

with open(“names.txt”, “r”, encoding=”utf-8″) as file:

    names = file.readlines()

for name in names:

    name = name.strip()

    if name:

        print(“Welcome,”, name)

इथे:

  1. File read केली
  2. Lines मिळवल्या
  3. strip() वापरलं
  4. Empty lines टाळल्या
  5. प्रत्येक name वर operation केला

अशी छोटी processing पुढे मोठ्या data-processing programs मध्ये उपयोगी पडते.

User ने चुकीचा filename दिला किंवा expected file तयारच झाली नाही, तर:

with open(“users.txt”, “r”) as file:

    data = file.read()

यामुळे FileNotFoundError येऊ शकतो. म्हणून गरज असेल तिथे exception handling वापरा.

try:

    with open(“users.txt”, “r”, encoding=”utf-8″) as file:

        data = file.read()

    print(data)

except FileNotFoundError:

    print(“users.txt file सापडली नाही.”)

User-facing application मध्ये हा approach जास्त चांगला आहे, कारण raw Python error दाखवण्यापेक्षा समजण्यासारखा message देता येतो.

FileNotFoundError

File सापडली नाही.

FileExistsError

x mode वापरताना file आधीपासून आहे.

PermissionError

File access करण्याची permission नाही.

IsADirectoryError

File अपेक्षित असताना directory path दिला आहे.

उदाहरण:

try:

    with open(“data.txt”, “r”, encoding=”utf-8″) as file:

        print(file.read())

except FileNotFoundError:

    print(“File सापडली नाही.”)

except PermissionError:

    print(“File access करण्याची permission नाही.”)

प्रत्येक possible exception पकडायची गरज नसते

File read करताना Python file मधील current position track करतो. ती position पाहण्यासाठी:

with open(“data.txt”, “r”, encoding=”utf-8″) as file:

    print(file.tell())

seek() वापरून position बदलता येते:

with open(“data.txt”, “r”, encoding=”utf-8″) as file:

    print(file.read(5))

    file.seek(0)

    print(file.read(5))

seek(0) मुळे position पुन्हा सुरुवातीला जाते. हे concepts सुरुवातीला फारसे वापरावे लागणार नाहीत, पण files मधून specific position वर data वाचताना उपयोगी पडतात.

आपण आतापर्यंत text files वापरल्या.

पण image, PDF किंवा इतर binary content सोबत काम करताना binary mode लागतो.

उदाहरण:

with open(“photo.jpg”, “rb”) as file:

    data = file.read()

इथे:

  • r → read
  • b → binary

म्हणजे rb → read binary.

Binary data write करण्यासाठी:

with open(“copy.jpg”, “wb”) as file:

    file.write(data)

Text file आणि binary file एकाच पद्धतीने handle होत नाहीत, म्हणून mode योग्य निवडणं महत्त्वाचं आहे.

समजा आपल्याकडे students ची माहिती आहे:

Name,Age,City

Rahul,22,Pune

Amit,21,Nashik

Sneha,23,Mumbai

हा CSV data आहे. Python मध्ये built-in csv module वापरता येतो.

import csv

with open(“students.csv”, “r”, newline=””, encoding=”utf-8″) as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

Output:

[‘Name’, ‘Age’, ‘City’]

[‘Rahul’, ’22’, ‘Pune’]

[‘Amit’, ’21’, ‘Nashik’]

[‘Sneha’, ’23’, ‘Mumbai’]

CSV useful आहे जेव्हा data rows आणि columns मध्ये naturally बसतो.

  • Data कायमस्वरूपी साठवण्यासाठी: प्रोग्राम बंद झाला तरी data नष्ट होऊ नये यासाठी.
  • External files सोबत काम करण्यासाठी: .txt, .csv, .json यासारख्या files मधील माहिती वापरण्यासाठी.
  • मोठ्या data चं efficient management: संपूर्ण data एकाच वेळी memory मध्ये न ठेवता, हवा तेवढाच भाग वाचता येतो.
  • Automation साठी: config files वाचणं, logs साठवणं, reports generate करणं यासारखी कामं आपोआप करण्यासाठी.

Python मध्ये कोणतीही file उघडण्यासाठी built-in open() function वापरलं जातं. या function ला file चं नाव (किंवा path) आणि mode हे दोन arguments दिले जातात.

file = open('filename.txt', 'mode')

  • filename.txt — जी file उघडायची आहे तिचं नाव किंवा संपूर्ण path.
  • mode — file कोणत्या प्रकारे उघडायची आहे (फक्त वाचण्यासाठी, लिहिण्यासाठी, जोडण्यासाठी इ.)

लक्षात ठेवा: जर mode दिला नाही, तर Python आपोआप 'r' (read mode) वापरतो.

f = open("data.txt", "r") print(f)

वरील code data.txt ही file read mode मध्ये उघडतो. जर file अस्तित्वात असेल, तर तो त्या file शी जोडलेला एक file object return करतो; file नसेल तर Python FileNotFoundError ही error देतो.

वरील code data.txt ही file read mode मध्ये उघडतो. जर file अस्तित्वात असेल, तर तो त्या file शी जोडलेला एक file object return करतो; file नसेल तर Python FileNotFoundError ही error देतो.

Modeपूर्ण नावउपयोग
rReadफक्त वाचण्यासाठी (default). File नसेल तर error येते.
wWriteलिहिण्यासाठी. File नसेल तर नवीन तयार होते; असेल तर जुना content पूर्ण मिटतो.
aAppendशेवटी नवीन data जोडण्यासाठी. जुना content कायम राहतो.
r+Read + Writeवाचणे आणि लिहिणे दोन्ही; file अस्तित्वात असावी लागते.
w+Write + Readलिहिणे व वाचणे; जुना content मिटतो.
a+Append + Readजोडणे व वाचणे; जुना content कायम राहतो.
rb / wbBinary Read/Writeimages, pdf यासारख्या binary files साठी.

file.close() ही method file बंद करते आणि त्यासाठी वापरलेले system resources मोकळे करते. जर file write किंवा append mode मध्ये उघडली असेल, तर close() केल्यावरच सर्व बदल (changes) व्यवस्थित save होतात याची खात्री होते.

file = open("data.txt", "r") # file वर काम करा file.close()

File उघडल्यानंतर ती close न केल्यास memory leak आणि data corruption सारख्या समस्या येऊ शकतात. पुढे आपण with statement शिकणार आहोत, जे हे काम आपोआप करतं.

File उघडल्यानंतर तिच्याबद्दलची काही महत्त्वाची माहिती आपण तपासू शकतो:

f = open("data.txt", "r") print("Filename:", f.name) print("Mode:", f.mode) print("Is Closed?", f.closed) f.close() print("Is Closed?", f.closed)

Filename: data.txt Mode: r Is Closed? False Is Closed? True

  • f.name: उघडलेल्या file चं नाव देतं.
  • f.mode: file कोणत्या mode मध्ये उघडली आहे ते सांगतं.
  • f.closed: file बंद आहे की उघडी आहे हे Boolean मध्ये (True/False) सांगतं.

File मधील content वाचण्यासाठी तीन प्रमुख methods वापरल्या जातात:

file = open("data.txt", "r") content = file.read() print(content) file.close()

file = open("data.txt", "r") print(file.readline()) # पहिली ओळ print(file.readline()) # दुसरी ओळ file.close()

file = open("data.txt", "r") lines = file.readlines() print(lines) file.close()

मोठ्या files साठी संपूर्ण content एकदम read() ने वाचण्याऐवजी, ओळीओळीने (for line in file:) वाचणं जास्त memory-efficient असतं.

"w" mode वापरून file मध्ये data लिहिता येतो. ही file अस्तित्वात नसेल तर नवीन तयार होते, आणि असेल तर जुना content पूर्णपणे मिटून नवीन content लिहिला जातो.

with open("data.txt", "w") as file: file.write("Namaste, Python!\n") file.write("File handling Python madhe khup sope aahe.") print("File successfully written")

File successfully written

with open("data.txt", "a") as file: file.write("\nHi appended line.")

write() single string लिहिण्यासाठी वापरतात, तर multiple lines एकाच वेळी लिहायच्या असल्यास writelines() (list of strings) वापरतात.

File manually उघडून, काम करून, शेवटी close() करणं ऐवजी with statement वापरणं ही आजची best practice आहे. with statement वापरल्यास file आपोआप बंद होते जरी मध्येच एखादी error आली तरीही. यामुळे file corruption आणि resource leakage चा धोका खूप कमी होतो.

with open("data.txt", "r") as file: content = file.read() print(content) # इथे file आपोआप बंद झालेली असते

Google आणि Python community दोघेही file handling साठी with statement वापरण्याची शिफारस करतात — कारण ते readable, safe आणि error-proof आहे.

कधी कधी file अस्तित्वातच नसते, किंवा वाचताना काही अडचण येते. अशावेळी प्रोग्राम क्रॅश होऊ नये आणि file नेहमी नीट बंद व्हावी यासाठी try / except / finally वापरतात.

try: file = open("data.txt", "r") content = file.read() print(content) except FileNotFoundError as e: print("Error:", e) finally: file.close()

  • try block मध्ये error येण्याची शक्यता असलेला code असतो.
  • except block FileNotFoundError सारख्या specific errors handle करतो.
  • finally block मध्ये लिहिलेला code error आली तरीही नक्की चालतो – त्यामुळे file नेहमी बंद होते याची खात्री होते.
  • शक्यतो नेहमी with statement वापरा — manual close() विसरण्याची शक्यता राहत नाही.
  • File अस्तित्वात आहे की नाही याची खात्री करण्यासाठी try/except वापरा.
  • मोठ्या files साठी read() ऐवजी for line in file: वापरा.
  • Binary files (images, pdf) साठी "rb" / "wb" mode वापरा.

Problem 1: एक Python program लिहा जो user कडून त्याचं नाव विचारेल आणि "names.txt" file मध्ये append mode मध्ये साठवेल.

Problem 2: with statement वापरून एक file वाचा आणि त्यातील एकूण ओळींची संख्या (line count) print करा.

Problem 3: try/except वापरून अशी file उघडा जी अस्तित्वात नाही, आणि योग्य error message दाखवा.

Problem 4: एका file मधील सर्व शब्द (words) मोजणारा (word count) program लिहा.

Frequently Asked Questions (FAQ)

Q1. Python मध्ये file handling म्हणजे नक्की काय?

Ans: File handling म्हणजे Python प्रोग्रामच्या मदतीने file तयार करणे, उघडणे, वाचणे, लिहिणे आणि बंद करणे या क्रिया करणे — जेणेकरून data कायमस्वरूपी साठवता येतो.

Q2. Python मध्ये file उघडण्यासाठी कोणतं function वापरतात?

Ans: Python चं built-in open() function वापरून file उघडली जाते. यासाठी filename आणि mode हे दोन arguments लागतात.

Q3. with statement वापरण्याचा फायदा काय?

Ans: with statement वापरल्यास file वापरून झाल्यावर ती आपोआप बंद होते, जरी error आली तरीही — त्यामुळे manually close() लिहिण्याची गरज पडत नाही.

Q4. “w” आणि “a” mode मध्ये काय फरक आहे?

Ans: “w” mode जुना content मिटवून नवीन content लिहितो, तर “a” mode जुना content कायम ठेवून शेवटी नवीन data जोडतो (append करतो).

Q5. File अस्तित्वात नसेल तर काय error येते?

Ans: Read mode (“r”) मध्ये file अस्तित्वात नसल्यास Python FileNotFoundError ही exception देतो.

Q6. read(), readline() आणि readlines() मध्ये फरक काय?

Ans: read() संपूर्ण content एकत्र वाचतो, readline() एका वेळी एक ओळ वाचतो, तर readlines() सर्व ओळी एका list मध्ये वाचतो.

File Handling शिकल्यानंतर पुढे Exception Handling सखोल पद्धतीने, तसेच Python Database (SQLite/MySQL) कसं वापरायचं हे शिकणं उपयुक्त ठरेल.

Blogger Rupesh

Blogger Rupesh

माझं नाव रुपेश आहे, आणि मी एक Blogger तसेच Content Writer आहे. मी माझा ब्लॉगिंगचा प्रवास वयाच्या ३० व्या वर्षी सुरू केला आणि आज मला या क्षेत्रात ५ वर्षांचा अनुभव आहे.माझा ब्लॉग “Learn Grow” मराठी भाषेत असून, त्यावर मी Blogging, Education, Programming शिकणे आणि AI Tools यांसारख्या महत्त्वाच्या विषयांवर सोप्या आणि समजण्यासारख्या भाषेत माहिती शेअर करतो. यासोबतच, मी Freelancing Services देखील प्रदान करतो, ज्यामध्ये Content Writing, SEO आणि Digital Marketing संबंधित कामांचा समावेश आहे.

Scroll to Top