PythonPython · Chapterبەش 10 · Lectureوانە 10.4

Moving in a File and Saving Python Objectsجووڵە لەناو فایلێکدا و هەڵگرتنی ئۆبجێکتەکانی Python

The file position: tell() and seek() with their text-mode limits, writing and reading through one file object, and saving Python objects with pickle (records until EOFError, never untrusted files) or, more safely, JSON.

شوێن لە : tell() و seek() لەگەڵ سنوورەکانیان لە دۆخی دەقدا، نووسین و خوێندنەوە بە یەک و هەڵگرتنی بە pickle ( تا EOFError، هەرگیز نەناسراو) یان، بە بێمەترسیتر، JSON.

13 min read13 خولەک خوێندنەوە · 12 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Read the file position with tell() and move it with seek(), from the start, the current position or the end.
  • Say which moves text mode allows and why binary mode allows every move.
  • Write and read through one file object with w+ and r+.
  • Save and load Python objects with pickle, read many records until EOFError, and explain why untrusted pickles are dangerous.
  • Choose JSON for simple data that people or other languages must read.
  • شوێنی بە tell() بزانیت و بە seek() بیجووڵێنیت، لە سەرەتاوە، لە شوێنی ئێستاوە یان لە کۆتاییەوە.
  • بڵێیت دۆخی دەق ڕێگە بە کام جووڵانە دەدات و بۆچی دۆخی دووانی ڕێگە بە هەموو جووڵەیەک دەدات.
  • بە w+ و r+ لە ڕێگەی یەک بنووسیت و بخوێنیتەوە.
  • بە pickle هەڵبگریت و بیانگەڕێنیتەوە، چەندین تا EOFError بخوێنیتەوە و ڕوون بکەیتەوە بۆچی pickleـی نەناسراو مەترسیدارە.
  • JSON بۆ سادە هەڵبژێریت کە خەڵک یان زمانەکانی تر دەبێت بیخوێننەوە.

Where the next read happensخوێندنەوەی داهاتوو لە کوێ دەبێت

In Reading and Writing Files every program read a file from the start to the end, or wrote it in one go. This lesson adds two skills. First, a file object remembers a position, and you can move it to read or write anywhere in the file. Second, you can save whole Python objects, such as a list of shop items, and load them back later with pickle or JSON.

لە وانەی خوێندنەوە و نووسینی فایلەکان هەموو لە سەرەتاوە تا کۆتایی دەخوێندەوە، یان بە یەک جار دەینووسی. ئەم وانەیە دوو توانا زیاد دەکات. یەکەم، شوێنێک لە بیر دەگرێت و دەتوانیت بیجووڵێنیت بۆ ئەوەی لە هەر جێیەکی بخوێنیتەوە یان بنووسیت. دووەم، دەتوانیت ، وەک کاڵاکانی دوکانێک، بە تەواوی هەڵبگریت و دواتر بە pickle یان JSON بیانگەڕێنیتەوە.

Quick checkپشکنینی خێراA program has just read the first line of marks.txt with f.readline(). Where does the next f.readline() start? تازە یەکەم دێڕی marks.txtـی بە f.readline() خوێندووەتەوە. f.readline()ـی داهاتوو لە کوێوە دەست پێ دەکات؟

The file position: tell() and seek()شوێن لە فایلدا: ⁦tell()⁩ و ⁦seek()⁩

A file object remembers a position: the place where the next read or write happens. Every read(), readline() and write() moves it on. tell() reports the position, and seek() moves it to another place, so a program can jump instead of always reading from the start to the end:

شوێنێک لە بیر دەگرێت: ئەو جێگایەی خوێندنەوە یان نووسینی داهاتوو تێیدا ڕوو دەدات. هەموو read()، readline() و write()ـێک دەیباتە پێشەوە. tell() شوێنەکە ڕادەگەیەنێت و seek() دەیگوازێتەوە بۆ جێگایەکی تر، بۆیە دەتوانێت باز بدات لەبری ئەوەی هەمیشە لە سەرەتاوە تا کۆتایی بخوێنێتەوە:

Watching the positionچاودێریکردنی شوێنەکەtell_seek.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as f:
    print("start:", f.tell())
    print(repr(f.readline()), "-> now at", f.tell())
    print(repr(f.readline()), "-> now at", f.tell())
    f.seek(0)                          # back to the start
    print("after seek(0):", f.tell())
    print(repr(f.readline()))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

'Aram 17\n' is 8 characters, so the position moves from 0 to 8.

'Aram 17\n' 8 ، بۆیە شوێنەکە لە 0ـەوە دەچێتە 8.

Lineدێڕی 5

seek(0) jumps back to the start of the file.

seek(0) باز دەداتەوە بۆ سەرەتای .

Animation in six frames. The file marks.txt is shown as three lines with their positions 0, 8, 18 and 28. An orange arrow marks the file position. Frame 1: the file is opened and the arrow is at 0. Frames 2 to 4: each readline() returns one line, with its newline, and the arrow jumps to 8, then 18, then 28. Frame 5: readline() at the end returns an empty string and the arrow stays at 28. Frame 6: seek(0) moves the arrow back to 0.
Animation in six frames. The file marks.txt is shown as three lines with their positions 0, 8, 18 and 28. An orange arrow marks the file position. Frame 1: the file is opened and the arrow is at 0. Frames 2 to 4: each readline() returns one line, with its newline, and the arrow jumps to 8, then 18, then 28. Frame 5: readline() at the end returns an empty string and the arrow stays at 28. Frame 6: seek(0) moves the arrow back to 0.
readline() moves the position one line at a time; at the end it returns ''; seek(0) goes back to the start.⁦readline()⁩ شوێنەکە دێڕ بە دێڕ دەباتە پێشەوە؛ لە کۆتاییدا '' دەگەڕێنێتەوە؛ ⁦seek(0)⁩ دەگەڕێتەوە بۆ سەرەتا.CêIT

seek(offset, whence) counts the offset from one of three reference points (whence): 0 = the start of the file (the default), 1 = the current position, 2 = the end of the file. A common use is a bookmark: remember a place with tell() and come back to it later with seek():

seek(offset, whence) ژمارەی offset لە یەکێک لە سێ خاڵی سەرچاوە (whence) دەژمێرێت: 0 = سەرەتای (بنەڕەت)، 1 = شوێنی ئێستا، 2 = کۆتایی . بەکارهێنانێکی باو نیشانەی پەڕەیە: شوێنێک بە tell() لە بیر بگرە و دواتر بە seek() بگەڕێوە بۆی:

tell() as a bookmark⁦tell()⁩ وەک نیشانەی پەڕەtell_bookmark.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as f:
    f.readline()
    place = f.tell()                   # remember this place
    print(repr(f.readline()))
    print(repr(f.readline()))
    f.seek(place)                      # jump back to the remembered place
    print(repr(f.readline()))
Quick checkپشکنینی خێراA file object has just read the first line of marks.txt ('Aram 17\n'). What does f.tell() show? تازە یەکەم دێڕی marks.txtـی خوێندووەتەوە ('Aram 17\n'). f.tell() چی پیشان دەدات؟

The file position: tell() and seek()شوێن لە فایلدا: ⁦tell()⁩ و ⁦seek()⁩

seek() in text mode: only a few moves⁦seek()⁩ لە دۆخی دەقدا: تەنها چەند جووڵەیەک

In text mode Python allows only these moves: seek(0) (the start), seek(0, 2) (the end), seek(0, 1) (stay) and seek(p) with a number p that tell() gave you. Moving from the current position or from the end by any other number is not allowed:

لە دۆخی دەقدا تەنها ڕێگە بەم جووڵانە دەدات: seek(0) (سەرەتا)، seek(0, 2) (کۆتایی)، seek(0, 1) (لە شوێنی خۆی) و seek(p) بە ژمارەیەکی p کە tell() پێی داویت. جووڵە لە شوێنی ئێستاوە یان لە کۆتاییەوە بە هەر ژمارەیەکی تر ڕێگەپێدراو نییە:

A relative seek in text mode⁦seek()⁩ـی ڕێژەیی لە دۆخی دەقداseek_text_error.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as f:
    f.seek(3, 1)                       # 3 forward from here, in text mode

You can see it with Kurdish text: the first line has 5 characters, but tell() says 9, because it counts the bytes of the four two-byte letters and the newline:

لە دەقی کوردیدا دەیبینیت: دێڕی یەکەم 5 هەیە، بەڵام tell() دەڵێت 9، چونکە چوار پیتە دوو بایتییەکە و دێڕە نوێکە دەژمێرێت:

tell() is not a character count⁦tell()⁩ ژمارەی نووسەکان نییەtell_kurdish.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("greeting.txt", "w", encoding="utf-8") as f:
    f.write("سڵاو\nHello\n")

with open("greeting.txt", encoding="utf-8") as f:
    line = f.readline()
    print(repr(line), len(line), "characters")
    print("tell():", f.tell())
Quick checkپشکنینی خێراWhich call works in text mode?کام بانگکردن لە دۆخی دەقدا کار دەکات؟

The file position: tell() and seek()شوێن لە فایلدا: ⁦tell()⁩ و ⁦seek()⁩

seek() in binary mode: every move worksseek() لە دۆخی دووانیدا: هەموو جووڵەیەک کار دەکات

In binary mode positions are plain byte numbers and every move works, also from the current position and from the end:

لە دۆخی دووانیدا شوێنەکان تەنها ژمارەی و هەموو جووڵەیەک کار دەکات، لە شوێنی ئێستا و لە کۆتاییشەوە:

seek() in binary mode⁦seek()⁩ لە دۆخی دووانیداseek_binary.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", "rb") as f:     # binary mode: positions are bytes
    f.seek(5)                          # 5 bytes from the start (reference 0)
    print(f.read(2))
    f.seek(1, 1)                       # 1 byte on from here (reference 1)
    print(f.read(6))
    f.seek(-3, 2)                      # 3 bytes back from the end (reference 2)
    print(f.read())
    print("now at", f.tell())
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-3

Byte 5 is where 17 starts in Aram 17.

5 ئەو شوێنەیە کە 17 لە Aram 17ـدا دەست پێ دەکات.

Lineدێڕی 4-5

One byte on skips the newline; the next 6 bytes are Shilan.

یەک بۆ پێشەوە بازی بەسەر دێڕە نوێکەدا دەدات؛ 6 داهاتوو Shilanـن.

Lineدێڕی 6-7

3 bytes back from the end: 15 and the last newline.

3 بۆ دواوە لە کۆتاییەوە: 15 و دوایین دێڕی نوێ.

CallبانگکردنMeaningماناText modeدۆخی دەقBinary modeدۆخی دووانی
f.seek(0)back to the startگەڕانەوە بۆ سەرەتا✓✓
f.seek(p)to p, a number from tell()بۆ p، ژمارەیەک لە tell()ـەوە✓✓
f.seek(0, 2)to the endبۆ کۆتایی✓✓
f.seek(5)to byte 5بۆ 5only if 5 came from tell()تەنها ئەگەر 5 لە tell()ـەوە هاتبێت✓
f.seek(3, 1)3 on from here3 بۆ پێشەوە لێرەوە✗✓
f.seek(-3, 2)3 back from the end3 بۆ دواوە لە کۆتاییەوە✗✓
Quick checkپشکنینی خێراmarks.txt is 28 bytes long and is opened with "rb". After f.seek(-3, 2), what does f.tell() give?marks.txt ⁦28⁩ و بە "rb" کراوەتەوە. دوای f.seek(-3, 2)، f.tell() چی دەدات؟

The file position: tell() and seek()شوێن لە فایلدا: ⁦tell()⁩ و ⁦seek()⁩

Writing and reading with one file objectنووسین و خوێندنەوە بە یەک ئۆبجێکتی فایل

Modes with + read and write through one file object, but there is only one position. After writing, the position is at the end, so reading gives nothing:

دۆخەکانی + لە ڕێگەی یەک دەخوێننەوە و دەنووسن، بەڵام تەنها یەک شوێن هەیە. دوای نووسین شوێنەکە لە کۆتاییدایە، بۆیە خوێندنەوە هیچ نادات:

Reading straight after writingخوێندنەوە ڕاستەوخۆ دوای نووسینw_plus_forgot.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("report.txt", "w+", encoding="utf-8") as f:
    f.write("Aram: 3 teas\n")
    print(repr(f.read()))              # reads from the end: nothing

Move back to the start with seek(0) before reading:

پێش خوێندنەوە بە seek(0) بگەڕێوە بۆ سەرەتا:

w+: write, seek(0), read⁦w+⁩: بنووسە، ⁦seek(0)⁩، بخوێنەوەw_plus.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("report.txt", "w+", encoding="utf-8") as f:
    f.write("Aram: 3 teas\n")
    f.write("Shilan: 2 coffees\n")
    print("Position after writing:", f.tell())
    f.seek(0)                          # go back before reading
    print(f.read(), end="")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

31=13+1831 = 13 + 18 characters written so far.

31=13+1831 = 13 + 18 کە تا ئێستا نووسراون.

Lineدێڕی 5

Without this line, read() would return ''.

بەبێ ئەم دێڕە، read() '' دەگەڕێنێتەوە.

r+ keeps the old content and starts at the beginning. If you read everything first, the position is at the end, so a following write() adds a line there:

r+ ناوەڕۆکی کۆن دەهێڵێتەوە و لە سەرەتاوە دەست پێ دەکات. ئەگەر سەرەتا هەمووی بخوێنیتەوە، شوێنەکە لە کۆتاییدایە، بۆیە write()ـی دواتر دێڕێک لەوێ زیاد دەکات:

r+: read, then add at the end⁦r+⁩: بخوێنەوە، پاشان لە کۆتاییدا زیاد بکەr_plus.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", "r+", encoding="utf-8") as f:
    print(f.read(), end="")            # read first: now we are at the end
    f.write("Hana 20\n")               # so the new line goes at the end
    f.seek(0)
    print("---")
    print(f.read(), end="")
Quick checkپشکنینی خێراA program opens a file with "w+", writes two lines and calls f.read(). What does it get? بە "w+" دەکاتەوە، دوو دێڕ دەنووسێت و f.read() بانگ دەکات. چی وەردەگرێت؟

Saving Python objects: pickleهەڵگرتنی ئۆبجێکتەکانی Python: pickle

Text files store strings. But a program's data are often lists and dictionaries: a shop's items, a game's level and score. Turning such an object into a row of bytes (or text) that can be saved in a file or sent over a network is called ; turning it back into an object is deserialization. Python's pickle module does both for almost any Python object. Python calls it pickling and unpickling.

هەڵدەگرن. بەڵام زۆرجار و : کاڵاکانی دوکانێک، ئاست و خاڵەکانی یارییەک. گۆڕینی لەو جۆرە بۆ ڕیزێک (یان دەق) کە بتوانرێت لە هەڵبگیرێت یان بە بنێردرێت پێی دەوترێت ؛ گەڕاندنەوەشی بۆ پێچەوانەکەیەتی. pickleـی هەردووکیان بۆ نزیکەی هەموو دەکات. پێی دەڵێت pickling و unpickling.

Pickles in a jarتورشی لە شووشەدا

In autumn a family puts vegetables into jars as pickles («تورشی») and opens them months later, still good. pickle.dump() puts a Python object into a file in the same way, and pickle.load() takes it out again, the same list or dictionary as before.

لە پاییزدا خێزانێک سەوزە دەکەنە ناو شووشە وەک تورشی و چەند مانگێک دواتر دەیکەنەوە، هێشتا باشە. pickle.dump() بە هەمان شێوە دەخاتە ناو و pickle.load() دیسان دەریدەهێنێتەوە، هەمان یان وەک پێشتر.

Where the analogy stops workingسنووری ئەم نموونەیە

A jar of pickles is safe to open. A pickle file from a stranger is not: see the warning below.

کردنەوەی شووشەیەک تورشی بێ مەترسییە. pickle لە کەسێکی نەناسراوەوە وا نییە: ئاگادارکردنەوەکەی خوارەوە ببینە.

dump() a dictionary, load() it backفەرهەنگێک ⁦dump()⁩ بکە، بە ⁦load()⁩ بیگەڕێنەوەpickle_one.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import pickle

item = {"code": 101, "name": "tea glass", "quantity": 48, "price": 750}

with open("item.dat", "wb") as f:      # pickle needs binary mode
    pickle.dump(item, f)

with open("item.dat", "rb") as f:
    print(f.read()[:24])               # not text a person can read

with open("item.dat", "rb") as f:
    copy = pickle.load(f)
print(copy)
print(type(copy), copy["price"] * copy["quantity"])
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5-6

pickle.dump(object, file) needs a file opened for binary writing: "wb".

pickle.dump(object, file) پێویستی بە هەیە کە بۆ نووسینی دووانی کرابێتەوە: "wb".

Lineدێڕی 8-9

The file holds bytes, not readable text.

هەڵدەگرێت، نەک دەقی خوێندراوە.

Lineدێڕی 11-12

pickle.load(file) with "rb" gives back a real dictionary.

pickle.load(file) بە "rb" ڕاستەقینە دەگەڕێنێتەوە.

Quick checkپشکنینی خێراWhich mode must a file have for pickle.dump()? بۆ pickle.dump() دەبێت بە کام دۆخ کرابێتەوە؟

WHAT Is "Pickle" In Python?! (EXTREMELY Useful!)Indently · Englishئینگلیزی · 116K viewsبینین · 2.9K likesلایک

Why JSON cannot save every Python object, how pickle.dump() and pickle.load() save and load one, and why unpickling untrusted files is dangerous.

بۆچی ناتوانێت هەموو پاشەکەوت بکات، pickle.dump() و pickle.load() چۆن پاشەکەوت و باری دەکەن و بۆچی بارکردنی pickle لە سەرچاوەی نەناسراو مەترسیدارە.

Whole video (9:31): saving to JSON (2:03) and its limits (3:48), pickle dump (5:05) and load (5:54), security risks (7:24).

هەموو ڤیدیۆکە ⁦(9:31)⁩: بە ⁦(2:03)⁩ و سنوورەکانی ⁦(3:48)⁩، pickle.dump ⁦(5:05)⁩ و pickle.load ⁦(5:54)⁩ و مەترسییە ئەمنییەکان ⁦(7:24)⁩.

Saving Python objects: pickleهەڵگرتنی ئۆبجێکتەکانی Python: pickle

Many records in one fileچەندین تۆمار لە یەک فایلدا

One dump() writes one object, so a file can hold many records one after another. load() reads them back one at a time, in the same order. When no record is left, load() raises EOFError (End Of File): the signal to stop. This shop program first asks how many items to save, saves their records and then lists them with their value in IQD:

هەر dump()ـێک یەک دەنووسێت، بۆیە دەتوانێت چەندین یەک لە دوای یەک هەڵبگرێت. load() یەک یەک و بە هەمان ڕیزبەندی دەیانخوێنێتەوە. کاتێک هیچ نەما، load() EOFError ⁦(End Of File)⁩ دروست دەکات: نیشانەی وەستان. ئەم دوکان سەرەتا دەپرسێت چەند کاڵا هەڵبگیرێت، ئەو کاڵایانە هەڵدەگرێت و پاشان لەگەڵ بەهاکەیان بە دیناری عێراقی ⁦(IQD)⁩ نیشانیان دەدات:

Item records with pickleتۆمارەکانی کاڵاکان بە picklepickle_shop.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import pickle

# 1. Save records: each one is a list [code, name, quantity, price]
count = int(input("How many items? "))
with open("items.dat", "ab") as f:     # ab: add to the end, binary
    for i in range(count):
        code = int(input("Item code: "))
        name = input("Name: ")
        quantity = int(input("Quantity: "))
        price = int(input("Price per item (IQD): "))
        pickle.dump([code, name, quantity, price], f)

# 2. Read them back, one load() for each record, until the end
print()
with open("items.dat", "rb") as f:
    while True:
        try:
            code, name, quantity, price = pickle.load(f)
        except EOFError:               # no more records
            break
        print(f"Item {code}: {name}, {quantity} × {price} IQD = {quantity * price} IQD")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

The user says first how many records to enter.

سەرەتا دەڵێت چەند دەنووسێت.

Lineدێڕی 5

"ab": add to the end of a binary file, so earlier records are kept.

"ab": زیادکردن بۆ کۆتایی ، بۆیە پێشوو دەمێننەوە.

Lineدێڕی 11

One dump() for each record.

یەک dump() بۆ هەر .

Lineدێڕی 16-20

Keep loading until EOFError says the file is finished.

بەردەوام بە load() بخوێنەوە تا EOFError دەڵێت تەواو بوو.

Lineدێڕی 21

The amount, quantity * price, is worked out when reading, so it is never stored twice.

بڕی پارەکە، quantity * price، لە کاتی خوێندنەوەدا دەژمێردرێت، بۆیە هەرگیز دوو جار هەڵناگیرێت.

Quick checkپشکنینی خێراWhy does the reading loop catch EOFError?بۆچی خوێندنەوە EOFError دەگرێت؟

Saving Python objects: pickleهەڵگرتنی ئۆبجێکتەکانی Python: pickle

Never unpickle data you do not trustهەرگیز دراوەیەک کە متمانەت پێی نییە unpickle مەکە

This is a kind of : data that a program only meant to read becomes code that runs. Pickle files also work only in Python: a program in another language cannot read them.

ئەمە جۆرێکە لە : ئەو تەنها ویستی بیخوێنێتەوە دەبێتە کۆدێک کە جێبەجێ دەبێت. pickle هەروەها تەنها لە کار دەکەن: بە زمانێکی تر ناتوانێت بیانخوێنێتەوە.

Quick checkپشکنینی خێراA classmate sends you scores.dat made with pickle. What is the safe choice?هاوپۆلێک scores.datـت بۆ دەنێرێت کە بە pickle دروستکراوە. هەڵبژاردنی بێمەترسی چییە؟

Saving Python objects: pickleهەڵگرتنی ئۆبجێکتەکانی Python: pickle

JSON: the safer text formatJSON: جۆرە دەقییە بێمەترسیترەکە

For simple data, such as numbers, strings, lists, dictionaries, True/False and None, JSON is usually the better choice. It is a text format: people can read it, programs in every language can read it (JSON: the language of APIs) and loading JSON never runs code. The json module has the same pair of functions:

بۆ سادە، وەک ژمارە، ، ، ، True/False و None، زۆرجار هەڵبژاردنی باشترە. جۆرێکی دەقییە: مرۆڤ دەتوانێت بیخوێنێتەوە، بە هەموو زمانێک دەتوانن بیخوێننەوە (JSON: زمانی APIـەکان) و بارکردنی JSON هەرگیز کۆد جێبەجێ ناکات. json هەمان جووتە هەیە:

The same items as JSONهەمان کاڵاکان بە JSONjson_shop.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import json

items = [{"code": 101, "name": "tea glass", "quantity": 48, "price": 750},
         {"code": 102, "name": "سەماوەر", "quantity": 3, "price": 45000}]

with open("items.json", "w", encoding="utf-8") as f:
    json.dump(items, f, ensure_ascii=False, indent=2)

with open("items.json", encoding="utf-8") as f:
    print(f.read())

with open("items.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded[1]["name"], loaded[1]["quantity"] * loaded[1]["price"])
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6

A JSON file is a text file: "w" with encoding="utf-8".

JSON : "w" لەگەڵ encoding="utf-8".

Lineدێڕی 7

ensure_ascii=False keeps Kurdish letters readable; indent=2 puts each value on its own line.

ensure_ascii=False پیتە کوردییەکان خوێندراوە دەهێڵێتەوە؛ indent=2 هەر لە دێڕی خۆیدا دادەنێت.

Lineدێڕی 13

json.load() gives back a list of dictionaries.

json.load() لە دەگەڕێنێتەوە.

JSON knows fewer types than Python. A tuple comes back as a list, and dates or your own classes need extra work:

JSON جۆری کەمتر لە دەناسێت. وەک دەگەڕێتەوە و بەروار یان خۆت کاری زیاتریان پێویستە:

A tuple comes back as a listتاپڵێک وەک لیست دەگەڕێتەوەjson_tuple.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import json

saved = {"place": ("Erbil", "Citadel"), "open": True, "phone": None}
text = json.dumps(saved)
print(text)
print(json.loads(text))                # the tuple comes back as a list
CompareبەراوردpicklepickleJSON
Formatجۆرbinaryدووانیtextدەقی
Who can read itکێ دەتوانێت بیخوێنێتەوەPython onlyتەنها people and every languageمرۆڤ و هەموو زمانێک
Typesجۆرەکانalmost any Python objectنزیکەی هەموو dict, list, str, int, float, bool, Nonedict، list، str، int، float، bool، None
Safe with files from others?لەگەڵ خەڵکی تر بێمەترسییە؟no: loading can run codeنەخێر: بارکردن دەتوانێت کۆد جێبەجێ بکاتyes: it is only dataبەڵێ: تەنها
Modesدۆخەکان"wb" / "rb""w" / "r", encoding="utf-8"
Quick checkپشکنینی خێراA program saves a list of student names and marks so that a web page written in another language can read it. Which format? لە ناو و نمرەی قوتابیان هەڵدەگرێت بۆ ئەوەی کە بە زمانێکی تر نووسراوە بتوانێت بیخوێنێتەوە. کام جۆر؟

How To Use JSON In PythonTech With Tim · Englishئینگلیزی · 253K viewsبینین · 6.2K likesلایک

What JSON is and how json.dump() and json.load() write Python data to a text file and read it back.

چییە و json.dump() و json.load() چۆن لە دەنووسن و دووبارە دەیخوێننەوە.

Whole video (6:11): JSON defined, loading and creating JSON strings, reading (3:46) and writing (4:51) JSON files.

هەموو ڤیدیۆکە ⁦(6:11)⁩: پێناسەی ، بارکردن و دروستکردنی ، پاشان خوێندنەوەی ⁦(3:46)⁩ و نووسینی ⁦(4:51)⁩ .

Common mistakesهەڵە باوەکان

MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
Reading straight after writing in w+ or r+خوێندنەوە ڕاستەوخۆ دوای نووسین لە w+ یان r+read() returns ''read() '' دەگەڕێنێتەوەf.seek(0)
f.seek(3, 1) or f.seek(-3, 2) in text modef.seek(3, 1) یان f.seek(-3, 2) لە دۆخی دەقداio.UnsupportedOperationbinary mode, or only seek(0), seek(0, 2) and values from tell()دۆخی دووانی، یان تەنها seek(0)، seek(0, 2) و ژمارەکانی tell()
Using tell() in text mode to count charactersبەکارهێنانی tell() لە دۆخی دەقدا بۆ ژماردنی wrong numbers with Kurdish text: tell() is an opaque number, not a countژمارەی هەڵە لەگەڵ دەقی کوردی: tell() ژمارەیەکی ناڕوونە، نەک ژماردنlen() of the text you read; tell() only to come back with seek()len()ـی ئەو دەقەی خوێندووتەتەوە؛ tell() تەنها بۆ گەڕانەوە بە seek()
pickle.dump() into a file opened with "w"pickle.dump() بۆ کە بە "w" کراوەتەوەTypeError: write() argument must be str, not bytes"wb" to write and "rb" to read a pickle file"wb" بۆ نووسین و "rb" بۆ خوێندنەوەی pickle
Unpickling a file from someone elseunpickleکردنی لە کەسێکی ترەوەhidden code can run on your computerکۆدی شاراوە دەتوانێت لەسەر جێبەجێ بێتJSON or CSV for shared dataJSON یان CSV بۆ هاوبەش
A fixed number of pickle.load() callsژمارەیەکی جێگیر لە بانگکردنی pickle.load()EOFError when the file holds fewer records than expectedEOFError کاتێک کەمتری تێدایە لەوەی چاوەڕێ دەکراload in a loop until EOFErrorلە load() بکە تا EOFError

Exercisesڕاهێنانەکان

ExerciseڕاهێنانUse and syntaxبەکارهێنان و شێوەی نووسین

Write the use and the syntax of open(), read(), seek() and pickle.dump(). (The first two come from Reading and Writing Files.)

بەکارهێنان و شێوەی نووسینی open()، read()، seek() و pickle.dump() بنووسە. (دووانی یەکەم لە وانەی خوێندنەوە و نووسینی فایلەکان فێر بوویت.)

Show answerوەڵامەکە پیشان بدە
  • f = open(name, mode, encoding="utf-8"): opens a file and returns its file object.
  • text = f.read(n): reads n characters, or with no number the rest of the file; '' at the end.
  • f.seek(offset, whence): moves the file position; whence 0 = start, 1 = current position, 2 = end (in text mode only seek(0), seek(0, 2) and tell() values).
  • pickle.dump(obj, f): writes a Python object to a file opened with "wb" or "ab".
  • f = open(name, mode, encoding="utf-8"): دەکاتەوە و دەگەڕێنێتەوە.
  • text = f.read(n): n دەخوێنێتەوە، یان بەبێ ژمارە پاشماوەی ؛ لە کۆتاییدا ''.
  • f.seek(offset, whence): شوێنی دەگوازێتەوە؛ whence 0 = سەرەتا، 1 = شوێنی ئێستا، 2 = کۆتایی (لە دۆخی دەقدا تەنها seek(0)، seek(0, 2) و ژمارەکانی tell()).
  • pickle.dump(obj, f): دەنووسێت بۆ کە بە "wb" یان "ab" کراوەتەوە.
ExerciseڕاهێنانPickling in your own wordspickling بە وشەی خۆت

Define pickling. Explain serialization and deserialization of a Python object.

pickling پێناسە بکە. و پێچەوانەکەی بۆ ڕوون بکەرەوە.

Show answerوەڵامەکە پیشان بدە

Serialization turns an object in memory (a list, a dictionary, a game state) into a stream of bytes or text that can be saved in a file, stored in a database or sent over a network. Deserialization turns that stream back into the same object. Pickling is Python's name for serializing with the pickle module (pickle.dump() into a "wb" file); unpickling is pickle.load() from an "rb" file. Only unpickle files you trust.

لە (، ، دۆخی یارییەک) دەگۆڕێت بۆ زنجیرەیەک یان دەق کە دەکرێت لە هەڵبگیرێت، لە خەزن بکرێت یان بە بنێردرێت. پێچەوانەکەی ئەو زنجیرەیە دەگەڕێنێتەوە بۆ هەمان . Pickling ناوی بۆ بە pickle (pickle.dump() بۆ بە "wb")؛ unpickling بریتییە لە pickle.load() لە بە "rb". تەنها ئەو unpickle بکە کە متمانەت پێیانە.

ExerciseڕاهێنانThe value of the whole stockبەهای هەموو کاڵاکان

items.dat holds item records [code, name, quantity, price] written with pickle.dump(), as in Many records in one file. Write a program that reads all of them and prints how many items there are and their total value in IQD (quantity * price, added up).

items.dat کاڵا [code, name, quantity, price] هەڵدەگرێت کە بە pickle.dump() نووسراون، وەک لە چەندین تۆمار لە یەک فایلدا. بنووسە کە هەموویان دەخوێنێتەوە و چاپ دەکات چەند کاڵا هەیە و کۆی بەهاکەیان بە IQD (quantity * price، کۆکراوە) چەندە.

Show answerوەڵامەکە پیشان بدە
items_total.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import pickle

grand_total = 0
count = 0
with open("items.dat", "rb") as f:
    while True:
        try:
            code, name, quantity, price = pickle.load(f)
        except EOFError:
            break
        grand_total += quantity * price
        count += 1
print(count, "items, worth", grand_total, "IQD in total")

Summaryپوختە

  • A file object remembers a position. tell() reports it; seek(offset, whence) moves it from the start (0), the current position (1) or the end (2).
  • In text mode only seek(0), seek(0, 2) and values from tell() work, and tell() is not a character count; binary mode allows every move.
  • + modes read and write through one position: call seek(0) before reading what you wrote.
  • pickle.dump() and pickle.load() save and load Python objects in binary files ("wb", "rb"); read many records until EOFError.
  • Never unpickle a file you do not trust: loading can run hidden code. For simple data shared with people or other languages, use JSON (json.dump(), json.load()).
  • شوێنێک لە بیر دەگرێت. tell() ڕایدەگەیەنێت؛ seek(offset, whence) لە سەرەتاوە ⁦(0)⁩، لە شوێنی ئێستاوە ⁦(1)⁩ یان لە کۆتاییەوە ⁦(2)⁩ دەیجووڵێنێت.
  • لە دۆخی دەقدا تەنها seek(0)، seek(0, 2) و ژمارەکانی tell() کار دەکەن و tell() ژماردنی نییە؛ دۆخی دووانی ڕێگە بە هەموو جووڵەیەک دەدات.
  • دۆخەکانی + لە ڕێگەی یەک شوێنەوە دەخوێننەوە و دەنووسن: پێش خوێندنەوەی ئەوەی نووسیوتە seek(0) بانگ بکە.
  • pickle.dump() و pickle.load() لە هەڵدەگرن و دەیانگەڕێننەوە ("wb"، "rb")؛ چەندین تا EOFError بخوێنەوە.
  • هەرگیز کە متمانەت پێی نییە unpickle مەکە: بارکردن دەتوانێت کۆدی شاراوە جێبەجێ بکات. بۆ سادە کە لەگەڵ خەڵک یان زمانەکانی تر هاوبەش دەکرێت JSON بەکار بهێنە (json.dump()، json.load()).

This lesson ends the chapter. The next chapter, on data structures and algorithms, starts with Stacks.

ئەم وانەیە کۆتایی بەشەکەیە. بەشی داهاتوو، دەربارەی و ، بە ستاکەکان دەست پێ دەکات.

Review questionsپرسیارەکانی پێداچوونەوە
Why does f.seek(3, 1) fail in text mode?بۆچی f.seek(3, 1) لە دۆخی دەقدا سەرناکەوێت؟

In text mode one character can be several bytes, so Python allows only seek(0), seek(0, 2) and positions from tell(). Relative moves need binary mode.

لە دۆخی دەقدا یەک دەکرێت چەند بێت، بۆیە تەنها ڕێگە بە seek(0)، seek(0, 2) و شوێنەکانی tell() دەدات. جووڵەی ڕێژەیی پێویستی بە دۆخی دووانی هەیە.

What does f.read() return straight after writing in "w+" mode?f.read() ڕاستەوخۆ دوای نووسین لە دۆخی "w+"ـدا چی دەگەڕێنێتەوە؟

'': the position is at the end. Call f.seek(0) first.

'': شوێنەکە لە کۆتاییدایە. سەرەتا f.seek(0) بانگ بکە.

Why must a program reading items.dat with pickle catch EOFError?بۆچی بەرنامەیەک کە items.dat بە pickle دەخوێنێتەوە دەبێت EOFError بگرێت؟

pickle.load() raises it when no object is left; it is the signal to stop reading.

pickle.load() کاتێک هیچ نەما دروستی دەکات؛ نیشانەی وەستانی خوێندنەوەیە.

Why is JSON safer than pickle for data from other people?بۆچی JSON بۆ دراوەیەک لە خەڵکی ترەوە لە pickle بێمەترسیترە؟

Loading JSON only builds lists, dictionaries, strings and numbers; loading a pickle can run hidden code.

بارکردنی JSON تەنها ، ، و ژمارە دروست دەکات؛ بارکردنی pickle دەتوانێت کۆدی شاراوە جێبەجێ بکات.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Stacks: Last In, First Outستاکەکان: دوایین هاتوو، یەکەم دەرچوو

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.