⚡0 XP🔥0

Ch 5 · Binary and CSV Files | बाइनरी और CSV फ़ाइल

Lesson 5 of 10 ⏱ 3 min read ❓ 5-question quiz ▶ Runs Python

Pickle module - dump() and load(); creating, reading, searching, appending and updating binary files; csv module - writer, writerow, writerows and reader.

Binary files with pickle#

Pickling (serialisation) converts a Python object into a byte stream; unpickling converts it back.

  • pickle.dump(obj, file) - write.
  • pickle.load(file) - read one object; raises EOFError at end of file.
▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

पिकलिंग में पायथन ऑब्जेक्ट को बाइट्स में बदलकर बाइनरी फ़ाइल में लिखा जाता है (dump) और पढ़ते समय वापस ऑब्जेक्ट में बदला जाता है (load)। फ़ाइल के अंत में load() EOFError देता है, इसलिए try-except का प्रयोग करते हैं।

Updating a binary file#

Read all records into a list, change the required one, then write everything back with mode wb (or use seek() with rb+).

CSV files#

▶ Try it YourselfPython
Ctrl + Enter to run

Use newline="" while opening CSV files so that extra blank lines are not added on Windows. Every value read from a CSV is a string.

हिंदी में समझें

CSV फ़ाइल में मान कॉमा से अलग होते हैं और इसे Excel में भी खोला जा सकता है। csv.writer से लिखते हैं (writerow/writerows) और csv.reader से पढ़ते हैं; पढ़े गए सभी मान स्ट्रिंग होते हैं।

Exam tips#

  • The 5-mark question often asks: write addRecord() and search() functions for a binary/CSV file.

Quick Quiz

Q1.

pickle.dump() is used to

Q2.

Error raised by pickle.load() at end of file is

Q3.

Mode to read a binary file is

Q4.

Values read using csv.reader are of type

Q5.

To write many rows at once use