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

Reading and Writing Filesخوێندنەوە و نووسینی فایلەکان

Keep data after a program ends: text and binary files, open() and its modes, paths, the with statement, writing and reading lines, turning lines into words and numbers, and the errors files cause.

دوای کۆتایی هاتنی بپارێزە: و ، open() و ، ، with، نووسین و خوێندنەوەی دێڕەکان، گۆڕینی دێڕەکان بۆ وشە و ژمارە و .

32 min read31 خولەک خوێندنەوە · 28 stepsهەنگاو

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

  • Explain why programs need files, and tell text files from binary files.
  • Open a file with the right mode and encoding="utf-8", and say which modes create, erase or start at the end.
  • Close files safely with with, and write text with write() and writelines().
  • Read files with read(), readline(), readlines() and a for loop, and turn lines into words and numbers.
  • Catch the errors files cause, such as FileNotFoundError and PermissionError, and write a complete program that saves and filters text.
  • ڕوون بکەیتەوە بۆچی پێویستیان بە هەیە و لە جیا بکەیتەوە.
  • بە دۆخی گونجاو و encoding="utf-8" بکەیتەوە و بڵێیت کام دۆخ دروست دەکات، دەسڕێتەوە یان لە کۆتاییەوە دەست پێ دەکات.
  • بە سەلامەتی بە with دابخەیت و دەق بە write() و writelines() بنووسیت.
  • بە read()، readline()، readlines() و بخوێنیتەوە و دێڕەکان بکەیت بە وشە و ژمارە.
  • بگریت (وەک FileNotFoundError و PermissionError) و تەواو بنووسیت کە دەق هەڵدەگرێت و دەیپاڵێوێت.

Why files? Variables forgetبۆچی فایل؟ گۆڕاوەکان لەبیر دەکەن

Every program so far forgot everything when it ended. Its variables live in (RAM) only while the program runs. Run this tea counter twice: the second run starts from zero again.

هەموو تا ئێستا کاتێک کۆتاییان هات هەموو شتێکیان لەبیر کرد. تەنها لە کاتی کارکردنی لە ⁦(RAM)⁩ـدا دەژین. ئەم چایە دوو جار کار پێ بکە: جاری دووەم دیسان لە سفرەوە دەست پێ دەکاتەوە.

A counter that forgetsژمێرەرێک کە لەبیری دەچێتtea_forget.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
total = 0                              # every run starts again from zero
teas = int(input("Teas sold just now: "))
total = total + teas
print("Teas sold today:", total)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

total is made again, as 0, every time the program starts.

total هەر جارێک دەست پێ دەکات دیسان وەک 0 دروست دەکرێتەوە.

To keep data for the next run, for tomorrow or for another program, a program saves it in a file on : a hard disk, an SSD or a flash drive. A file stays after the program ends and after the computer is switched off (Switch off: what stays and what goes explains why). This is how a shop keeps its stock, a school its marks and an office its staff list.

بۆ پاراستنی بۆ جاری داهاتوو، بۆ سبەی یان بۆ تر، لە لەسەر هەڵی دەگرێت: ، SSD یان . دوای کۆتایی هاتنی و دوای دەمێنێتەوە (کوژاندنەوە: چی دەمێنێت و چی دەڕوات هۆکارەکەی ڕوون دەکاتەوە). دوکانێک کاڵاکانی، قوتابخانەیەک نمرەکان و فەرمانگەیەک ناوی کارمەندەکانی بەم شێوەیە هەڵدەگرێت.

Definitionپێناسە

A named collection of stored on a computer, such as a document, a photo, a song or a . Its shows its type.

کۆمەڵێک ناونراوە کە لەسەر کۆمپیوتەر هەڵگیراوە، وەک بەڵگەنامەیەک، وێنەیەک، گۆرانییەک یان . جۆرەکەی پیشان دەدات.

The shopkeeper's notebookدەفتەرەکەی دوکاندار

A shopkeeper who only remembers in his head who owes him money forgets some of it by the next morning. Written in his notebook, every debt is still there tomorrow and next month. Variables are the memory in the head; a file is the notebook.

دوکاندارێک کە تەنها لە مێشکیدا بیری دەمێنێت کێ قەرزاریەتی، هەندێکی تا بەیانی لەبیر دەچێت. ئەگەر لە دەفتەرەکەیدا بینووسێت، هەموو قەرزێک سبەی و مانگی داهاتووش هەر لەوێیە. یادگەی ناو مێشکن؛ دەفتەرەکەیە.

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

A notebook is read by people. A file is read and written by programs, in an instant, and one wrong line of code can erase it, as you will see with the w mode.

دەفتەر خەڵک دەیخوێننەوە. لە چرکەیەکدا دەیخوێننەوە و دەینووسن و یەک دێڕی هەڵەی کۆد دەتوانێت بیسڕێتەوە، وەک لە دۆخی wـدا دەیبینیت.

Quick checkپشکنینی خێراA program asks for 30 marks and prints their average. The next day the teacher wants the marks again. Where are they? ⁦30⁩ نمرە وەردەگرێت و تێکڕاکەیان چاپ دەکات. ڕۆژی دواتر مامۆستا دیسان نمرەکانی دەوێت. لە کوێن؟

Why files? Variables forgetبۆچی فایل؟ گۆڕاوەکان لەبیر دەکەن

A counter that remembersژمێرەرێک کە لەبیری ناچێت

Here is the same counter with a file. It reads the old total from tea_total.txt, adds the new teas and writes the new total back. Now the second run continues from the first. Do not worry about the details yet: by the end of this lesson you can explain every line.

ئەمە هەمان بە . کۆی کۆن لە tea_total.txt دەخوێنێتەوە، چا نوێیەکان زیاد دەکات و کۆ نوێیەکە دەنووسێتەوە. ئێستا جاری دووەم لە شوێنی جاری یەکەمەوە بەردەوام دەبێت. ئێستا خەمی وردەکارییەکان مەخۆ: لە کۆتایی ئەم وانەیەدا دەتوانیت هەموو دێڕێک ڕوون بکەیتەوە.

The same counter, with a fileهەمان ژمێرەر، بە فایلێکtea_keep.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    with open("tea_total.txt", encoding="utf-8") as f:
        total = int(f.read())          # the number saved last time
except FileNotFoundError:
    total = 0                          # first run: no file yet

teas = int(input("Teas sold just now: "))
total = total + teas

with open("tea_total.txt", "w", encoding="utf-8") as f:
    f.write(str(total))                # saved for the next run
print("Teas sold today:", total)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-5

Read the saved total. The first time, the file does not exist yet, so start at 0.

کۆ هەڵگیراوەکە بخوێنەوە. جاری یەکەم هێشتا نییە، بۆیە لە 0ـەوە دەست پێ بکە.

Lineدێڕی 10-11

Write the new total into the file for the next run.

کۆ نوێیەکە بۆ جاری داهاتوو لە بنووسە.

Your .py programs are files too. The editor saves your code on the disk, and Python reads it from there every time you run it. The data a program works with can be kept in the same way.

.pyـی خۆشت . کۆدەکەت لەسەر دیسک هەڵدەگرێت و هەر جارێک کاری پێ دەکەیت لەوێوە دەیخوێنێتەوە. ئەو کاری لەگەڵ دەکات دەکرێت بە هەمان شێوە هەڵبگیرێت.

Text files and binary filesفایلە دەقییەکان و فایلە دووانییەکان

Inside the computer every file is a row of bytes, one after another. What those bytes mean decides the kind of file. There are two kinds of data files:

لەناو هەموو ڕیزێک ، یەک لە دوای یەک. مانای جۆری دیاری دەکات. دوو جۆر هەن:

KindجۆرWhat the bytes are چینExamplesنموونەOpen it withبە چی دەکرێتەوە
Text filecodes of characters; each line ends with a newline \nکۆدی ؛ هەر دێڕێک بە دێڕی نوێ \n کۆتایی دێت.txt .py .csv .htmlany text editor (Notepad, VS Code)هەر (Notepad، ⁦VS Code⁩)
Binary fileanything else: pixels, sound, machine code, packed partsهەر شتێکی تر: ، دەنگ، ، بەشی پەستێنراو.png .jpg .mp3 .mp4 .zip .exe .docxthe right program (a photo viewer, Word…) گونجاو (پیشاندەری وێنە، Word…)

In a text file each character is stored as its number in a . With UTF-8, English letters take one byte and Kurdish letters two (UTF-8: one to four bytes, Kurdish letters in a database). The end of a line is one more character, the newline \n. This program writes two short lines and then reads the file back as raw bytes:

لە هەر وەک ژمارەکەی لە هەڵدەگیرێت. بە ⁦UTF-8⁩ پیتە ئینگلیزییەکان یەک و پیتە کوردییەکان دوو دەگرن (⁦UTF-8⁩: یەک تا چوار بایت، پیتە کوردییەکان لە بنکەدراوەدا). کۆتایی دێڕ ترە، دێڕی نوێ \n. ئەم دوو دێڕی کورت دەنووسێت و پاشان وەک خاو دەخوێنێتەوە:

A text file is bytes tooفایلێکی دەقی هەر بایتەtext_bytes.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("hello.txt", "w", encoding="utf-8") as f:
    f.write("Hi Aram\n")
    f.write("سڵاو\n")

with open("hello.txt", "rb") as f:     # "rb": read the raw bytes
    data = f.read()

print(len(data), "bytes")
print(list(data))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

encoding="utf-8": store the characters with UTF-8.

encoding="utf-8": بە ⁦UTF-8⁩ هەڵبگرە.

Lineدێڕی 5

"rb" reads the bytes themselves, not characters.

"rb" خودی دەخوێنێتەوە، نەک .

72, 105 are H and i; 10 is \n. Each Kurdish letter took two bytes: 216, 179 is «س». A text editor does the opposite: it turns the codes back into letters and starts a new line at every 10.

72, 105 بریتین لە H و i؛ 10 بریتییە لە \n. هەر پیتێکی کوردی دوو گرت: 216, 179 بریتییە لە «س». پێچەوانەکەی دەکات: کۆدەکان دەکاتەوە بە پیت و لە هەر 10ـێکدا دێڕێکی نوێ دەست پێ دەکات.

Quick checkپشکنینی خێراWhich of these is a text file?کامیان ؟

Text files and binary filesفایلە دەقییەکان و فایلە دووانییەکان

Binary files are not textفایلە دووانییەکان دەق نین

In a binary file the bytes are not character codes, so they do not make sense as text. A text editor shows strange symbols, and Python refuses to read them as UTF-8. The first 8 bytes of every PNG picture show it:

لە کۆدی نین، بۆیە وەک دەق مانایان نییە. هێمای سەیر پیشان دەدات و ڕازی نابێت وەک ⁦UTF-8⁩ بیانخوێنێتەوە. یەکەم 8 هەموو وێنەیەکی PNG ئەمە پیشان دەدەن:

A picture opened as textوێنەیەک کە وەک دەق کراوەتەوەpng_as_text.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
# the first 8 bytes of every PNG picture
with open("tiny.png", "wb") as f:
    f.write(bytes([137, 80, 78, 71, 13, 10, 26, 10]))

with open("tiny.png", encoding="utf-8") as f:   # wrong: a picture is not text
    print(f.read())

Binary files are also fragile: change a single bit of a picture or a program and it may not open at all. A text file with one wrong letter can still be read and corrected by a person. Python can read and write both kinds; the mode you open the file with decides which.

ناسکیشن: تەنها یەک لە وێنەیەک یان بگۆڕە، لەوانەیە هەر نەکرێتەوە. کە یەک پیتی هەڵەی تێدایە هێشتا مرۆڤ دەتوانێت بیخوێنێتەوە و ڕاستی بکاتەوە. دەتوانێت هەردوو جۆر بخوێنێتەوە و بنووسێت؛ ئەو دۆخەی پێ دەکەیتەوە بڕیار دەدات کامیان.

Quick checkپشکنینی خێراA program opens photo.jpg with encoding="utf-8" and calls f.read(). What happens? photo.jpg بە encoding="utf-8" دەکاتەوە و f.read() بانگ دەکات. چی ڕوو دەدات؟

Text files and binary filesفایلە دەقییەکان و فایلە دووانییەکان

Try it: one name in .txt and in .docxتاقی بکەرەوە: یەک ناو لە ⁦.txt⁩ و لە ⁦.docx⁩

Save just one name, Shilan, in a text file and in a Word document, then compare the sizes. We did it on a computer (macOS):

تەنها یەک ناو، Shilan، لە و لە بەڵگەنامەیەکی Word هەڵبگرە، پاشان قەبارەکانیان بەراورد بکە. ئێمە لەسەر ⁦(macOS)⁩ کردمان:

FileSizeقەبارەWhat is insideچی تێدایە
name.txt6 bytesتەنها 6 the 6 letters S h i l a n, nothing else6 پیتەکەی ⁦S h i l a n⁩، هیچی تر
name.docx (made by the converter of macOS)name.docx (بە گۆڕەری macOS دروستکراو)3,484 bytes (about 3.4 KB)⁦3,484⁩ (نزیکەی ⁦3.4 KB⁩)a zip package of 8 parts: the text in XML, a design theme, information about the documentپاکەتێکی zip لە 8 بەش: دەقەکە بە XML، تێمێکی دیزاین، زانیاری دەربارەی بەڵگەنامەکە
name.docx (made from a Word template)name.docx (لە قاڵبێکی Word دروستکراو)36,581 bytes (about 36 KB)⁦36,581⁩ (نزیکەی ⁦36 KB⁩)17 parts: styles, fonts, settings, a theme, a small preview picture, author and dates…⁦17⁩ بەش: شێوازەکان، فۆنتەکان، ڕێکخستنەکان، تێمێک، وێنەیەکی بچووکی پێشبینین، نووسەر و بەروارەکان…

A .docx file is a binary file: a zip package. Most of it is not your text but formatting and information about the document, such as the author, the dates and the page settings. A .txt file holds only the characters, so its size is counted in bytes while the .docx needs kilobytes. (File extensions and file types lists more file types.)

.docx : پاکەتێکی zip. زۆربەی ناوەڕۆکەکەی دەقەکەی تۆ نییە، بەڵکو ڕێکخستنی شێوە و زانیاری دەربارەی بەڵگەنامەکەیە، وەک نووسەر، بەروارەکان و ڕێکخستنی پەڕە. .txt تەنها هەڵدەگرێت، بۆیە قەبارەکەی بە دەژمێردرێت، لە کاتێکدا .docx پێویستە. (پاشگرەکانی فایل و جۆرەکانی فایل جۆری زیاتر دەناسێنێت.)

Quick checkپشکنینی خێراWhy is the .docx file thousands of times bigger than the .txt file with the same name?بۆچی .docx هەزاران جار لە .txt بە هەمان ناو گەورەترە؟

Opening a file: open() and the file objectکردنەوەی فایلێک: ⁦open()⁩ و ئۆبجێکتی فایل

To work with a file, a program first opens it with the built-in function open(). It needs the file's name, a mode that says what you want to do, and for a text file the encoding:

بۆ کارکردن لەگەڵ ، سەرەتا بە open() دەیکاتەوە. ناوی ، دۆخێک کە دەڵێت دەتەوێت چی بکەیت و بۆ پێویستە:

Open a file and look at its file objectفایلێک بکەرەوە و سەیری ئۆبجێکتی فایلەکە بکەopen_attributes.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
f = open("notes.txt", "w", encoding="utf-8")
print("name:  ", f.name)
print("mode:  ", f.mode)
print("closed:", f.closed)
f.close()
print("closed:", f.closed)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

"notes.txt" is the name, "w" the mode (write), encoding="utf-8" the encoding.

"notes.txt" ناوەکەیە، "w" دۆخەکە (نووسین) و encoding="utf-8" .

Lineدێڕی 2-4

Three attributes describe the file object: its name, its mode and whether it is closed.

سێ باسی دەکەن: ناوەکەی، دۆخەکەی و ئایا داخراوە.

Lineدێڕی 5-6

After close(), closed is True.

دوای close()، closed دەبێتە True.

open() returns a file object (also called a file handle). The variable f is now your link to the file on the disk: everything you do with the file goes through f's methods (f.write(), f.read(), f.close()…), and its attributes f.name, f.mode and f.closed tell you about it.

open() دەگەڕێنێتەوە (هەروەها پێی دەڵێن ⁦file handle⁩). f ئێستا بەستەری تۆیە بە سەر دیسکەکەوە: هەر شتێک بە بکەیت بە fـدا تێدەپەڕێت (f.write()، f.read()، f.close()…) و f.name، f.mode و f.closed زانیاریت دەربارەی پێ دەدەن.

Definitionپێناسە

The that open() returns. It links the program to the on the disk: the program reads and writes through its methods (read(), write(), seek()…), its attributes (name, mode, closed) describe it, and close() ends the link.

ئەو open() دەیگەڕێنێتەوە. بە سەر دیسکەکەوە دەبەستێتەوە: لە ڕێگەی (read()، write()، seek()…) دەخوێنێتەوە و دەنووسێت، (name، mode، closed) باسی دەکەن و close() بەستنەوەکە کۆتایی پێ دەهێنێت.

Three parts side by side. On the left, the program in RAM with its variables and the file object f. In the middle, the file object, which knows the file's name, its mode and the current position. On the right, the file marks.txt on the disk. Arrows: write() carries text from the program to the file, read() carries text back. Under the program: switched off, RAM is emptied and the variables are gone. Under the disk: the file stays.سێ بەش لە تەنیشت یەکەوە. لای چەپ بەرنامەکە لە RAMـدا لەگەڵ گۆڕاوەکانی و ئۆبجێکتی فایلەکە f. لە ناوەڕاستدا ئۆبجێکتی فایلەکە کە ناوی فایلەکە، دۆخەکەی و شوێنی ئێستا دەزانێت. لای ڕاست فایلی marks.txt لەسەر دیسک. تیرەکان: write() دەق لە بەرنامەکەوە بۆ فایلەکە دەبات و read() دەق دەگەڕێنێتەوە. لە ژێر بەرنامەکەدا: کە کوژایەوە، RAM بەتاڵ دەبێت و گۆڕاوەکان نامێنن. لە ژێر دیسکەکەدا: فایلەکە دەمێنێتەوە.
The file object is the program's link to the file. RAM forgets at switch-off; the file on the disk stays. بەستەری بە . RAM لە کاتی لەبیری دەچێت؛ سەر دیسک دەمێنێتەوە.CêIT
Quick checkپشکنینی خێراWhat does open() give back?open() چی دەگەڕێنێتەوە؟

Opening a file: open() and the file objectکردنەوەی فایلێک: ⁦open()⁩ و ئۆبجێکتی فایل

Read mode never creates a fileدۆخی خوێندنەوە هەرگیز فایل دروست ناکات

If you give no mode, open() uses "r": read a text file. Reading a file that does not exist is an error:

ئەگەر هیچ دۆخێک نەدەیت، open() "r" بەکار دەهێنێت: خوێندنەوەی . خوێندنەوەی کە بوونی نییە :

Opening a missing file for readingکردنەوەی فایلێکی نەبوو بۆ خوێندنەوەopen_missing.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
f = open("shopping.txt", encoding="utf-8")   # read mode: the default
print(f.read())

Later in this lesson you will catch this error instead of crashing (Errors you will meet).

دواتر لەم وانەیەدا ئەم دەگریت لەبری ئەوەی بکەوێت (چەند هەڵەیەک کە تووشیان دەبیت).

Quick checkپشکنینی خێراshopping.txt does not exist. Which line creates it?shopping.txt بوونی نییە. کام دێڕ دروستی دەکات؟

Opening a file: open() and the file objectکردنەوەی فایلێک: ⁦open()⁩ و ئۆبجێکتی فایل

Files in other folders: pathsفایلەکان لە فۆڵدەرەکانی تردا: ڕێڕەوەکان

A plain name like "notes.txt" means the file in the current working directory: the folder Python was started in (when you press Run in an editor, usually your project folder). For a file somewhere else, give its path. Paths: a file's full address explains relative and absolute paths; in Python they look like this:

ناوێکی سادەی وەک "notes.txt" واتە ئەو لە کاری ئێستادایە: ئەو تێدا دەستی پێکرد (کاتێک لە Run دەکەیت، زۆرجار پڕۆژەکەت). بۆ لە شوێنێکی تر، بدە. ڕێڕەوەکان: ناونیشانی تەواوی فایلێک و ڕوون دەکاتەوە؛ لە بەم شێوەیەن:

Name given to open()ناوی دراو بە ⁦open()⁩Which fileکام
"marks.txt"marks.txt in the current foldermarks.txt لە ئێستادا
"data/marks.txt"marks.txt in the folder data inside the current folder (a relative path)marks.txt لە data لەناو ئێستادا ()
"C:/Users/Aram/Documents/marks.txt"a full (absolute) path on Windows لەسەر Windows
"/home/aram/marks.txt"an absolute path on Linux (macOS paths start with /Users/) لەسەر Linux ( macOS بە /Users/ دەست پێ دەکەن)

A writing mode can create a missing file, but not a missing folder. The same program fails while there is no data folder and works once the folder exists:

دۆخێکی نووسین دەتوانێت نەبوو دروست بکات، بەڵام نەبوو نا. هەمان تا data نەبێت سەرناکەوێت و کاتێک هەبوو کار دەکات:

A relative pathڕێڕەوێکی ڕێژەییpath_folder.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
# a relative path: the file marks.txt inside the folder data
with open("data/marks.txt", "w", encoding="utf-8") as f:
    f.write("Aram 17\n")
print("saved")

On Windows, paths use backslashes (\). Inside a string a backslash starts an escape sequence, so in "C:\new\marks.txt" the \n becomes a new line: the trap shown in Special characters. Write Windows paths with forward slashes, "C:/new/marks.txt" (Windows accepts them), or as a raw string, r"C:\new\marks.txt".

لە Windowsـدا هێمای \ (backslash) بەکار دەهێنن. لەناو ئەم هێمایە و پیتی دوای خۆی پێک دەهێنن، بۆیە لە "C:\new\marks.txt"ـدا \n دەبێتە دێڕی نوێ: ئەو تەڵەیەی لە بەشی نووسە تایبەتەکان بینیت. Windows بە هێمای / بنووسە، "C:/new/marks.txt" (Windows وەریان دەگرێت)، یان وەک خاو: r"C:\new\marks.txt".

Quick checkپشکنینی خێراPython runs in the folder shop (the current working directory). Which name opens stock.txt in shop/data? لە shopـدا کار دەکات ( کاری ئێستا). کام ناو stock.txt لە shop/dataـدا دەکاتەوە؟

File modes: read, write, appendدۆخەکانی کردنەوە: خوێندنەوە، نووسین، زیادکردن

The mode is the second argument of open(). One letter says the main job, + adds the other job (reading and writing) and b switches from text to binary. Before you open a file, ask three questions: Is a missing file created? Is the old content erased? Where does reading or writing start?

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

Definitionپێناسە

The letters given to open() that say what a program will do with a : read (r, the default), write (w), append (a), create a new file (x), read and write (+), binary (b) or text (t, the default). The mode decides whether a missing file is created, whether old content is erased and where reading or writing starts.

ئەو پیتانەی دەدرێنە open() و دەڵێن چی لە دەکات: خوێندنەوە (r، بنەڕەتییەکە)، نووسین (w)، زیادکردن بۆ کۆتایی (a)، دروستکردنی نوێ (x)، خوێندنەوە و نووسین (+)، دووانی (b) یان دەق (t، بنەڕەتییەکە). دۆخەکە بڕیار دەدات ئایا نەبوو دروست دەکرێت، ئایا ناوەڕۆکی کۆن دەسڕدرێتەوە و خوێندنەوە یان نووسین لە کوێوە دەست پێ دەکات.

Text modes. Add b for a binary file: rb, rb+, wb, wb+, ab, ab+ behave the same but read and write bytes.دۆخەکانی دەق. بۆ b زیاد بکە: rb، ⁦rb+⁩، wb، ⁦wb+⁩، ab، ⁦ab+⁩ هەمان شت دەکەن بەڵام دەخوێننەوە و دەنووسن.
ModeدۆخJobکارFile missing نییەOld contentناوەڕۆکی کۆنStarts atلە کوێوە دەست پێ دەکات
rread only (the default)تەنها خوێندنەوە (بنەڕەت)error: FileNotFoundError: FileNotFoundErrorkeptدەمێنێتstartسەرەتا
r+read and writeخوێندنەوە و نووسینerror: FileNotFoundError: FileNotFoundErrorkept (overwritten only where you write)دەمێنێت (تەنها لەو شوێنەی دەنووسیت جێی دەگیرێتەوە)startسەرەتا
wwrite onlyتەنها نووسینcreatedدروست دەکرێتerasedدەسڕدرێتەوەstartسەرەتا
w+write and readنووسین و خوێندنەوەcreatedدروست دەکرێتerasedدەسڕدرێتەوەstartسەرەتا
aappend: write at the endزیادکردن: نووسین لە کۆتاییداcreatedدروست دەکرێتkeptدەمێنێتendکۆتایی
a+append and readزیادکردن و خوێندنەوەcreatedدروست دەکرێتkeptدەمێنێتend (writing always goes to the end)کۆتایی (نووسین هەمیشە دەچێتە کۆتایی)
xcreate a new file and writeدروستکردنی نوێ و نووسینcreatedدروست دەکرێتerror if the file exists: FileExistsErrorئەگەر هەبێت : FileExistsErrorstartسەرەتا
Three rows show the same file, Aram 17 and Shilan 19, as a row of character boxes with a return sign for each newline. Row r and r+: the arrow points at the first box, the content is kept. Row w and w+: the boxes are crossed out because the content is erased, and the arrow points at the start of the empty file. Row a and a+: the content is kept and the arrow points after the last box, at the end.سێ ڕیز هەمان فایل پیشان دەدەن، Aram 17 و Shilan 19، وەک ڕیزێک سندوقی نووسە لەگەڵ نیشانەیەکی گەڕانەوە بۆ هەر دێڕێکی نوێ. ڕیزی r و r+: تیرەکە ئاماژە بە یەکەم سندوق دەکات، ناوەڕۆکەکە دەمێنێت. ڕیزی w و w+: سندوقەکان هێڵیان بەسەردا هاتووە چونکە ناوەڕۆکەکە دەسڕدرێتەوە و تیرەکە ئاماژە بە سەرەتای فایلی بەتاڵ دەکات. ڕیزی a و a+: ناوەڕۆکەکە دەمێنێت و تیرەکە ئاماژە بە دوای دوایین سندوق دەکات، واتە کۆتایی.
Where each mode starts: r at the start, w at the start of an emptied file, a at the end.هەر دۆخێک لە کوێوە دەست پێ دەکات: r لە سەرەتا، w لە سەرەتای بەتاڵکراو، a لە کۆتایی.CêIT
Quick checkپشکنینی خێراA shop program must add today's sales to sales.txt without losing yesterday's. Which mode? دوکانێک دەبێت فرۆشی ئەمڕۆ بۆ sales.txt زیاد بکات بەبێ ئەوەی فرۆشی دوێنێ ون بێت. کام دۆخ؟

File modes: read, write, appendدۆخەکانی کردنەوە: خوێندنەوە، نووسین، زیادکردن

Five more modes: rb+, wb, w+, ab, ab+پێنج دۆخی تر: ⁦rb+⁩، wb، ⁦w+⁩، ab و ⁦ab+⁩

The t for text is the default, so "r" means "rt". The three questions of the table describe every mode. Here are the five that the textbook's activity asks about:

t بۆ دەق بنەڕەتە، بۆیە "r" واتە "rt". سێ پرسیارەکەی خشتەکە باسی هەموو دۆخێک دەکەن. ئەمە ئەو پێنج دۆخەن کە چالاکییەکەی کتێبەکە پرسیاریان لێ دەکات:

  • rb+: read and write a binary file; it must exist; nothing is erased; starts at the beginning.
  • wb: write a binary file; created or erased; starts at the beginning.
  • w+: write and read a text file; created or erased; starts at the beginning.
  • ab: add to the end of a binary file; created if missing; starts at the end.
  • ab+: add to the end of a binary file and read it; created if missing; starts at the end.
  • rb+: خوێندنەوە و نووسینی ؛ دەبێت هەبێت؛ هیچ ناسڕدرێتەوە؛ لە سەرەتاوە دەست پێ دەکات.
  • wb: نووسینی ؛ دروست دەکرێت یان دەسڕدرێتەوە؛ لە سەرەتاوە دەست پێ دەکات.
  • w+: نووسین و خوێندنەوەی ؛ دروست دەکرێت یان دەسڕدرێتەوە؛ لە سەرەتاوە دەست پێ دەکات.
  • ab: زیادکردن بۆ کۆتایی ؛ ئەگەر نەبێت دروست دەکرێت؛ لە کۆتاییەوە دەست پێ دەکات.
  • ab+: زیادکردن بۆ کۆتایی و خوێندنەوەی؛ ئەگەر نەبێت دروست دەکرێت؛ لە کۆتاییەوە دەست پێ دەکات.
Quick checkپشکنینی خێراWhich mode erases a file the moment it is opened?کام دۆخ هەر لە کاتی کردنەوەیدا دەسڕێتەوە؟

File modes: read, write, appendدۆخەکانی کردنەوە: خوێندنەوە، نووسین، زیادکردن

We checked the table with Pythonخشتەکەمان بە Python پشکنی

A table in a book can be wrong, so we checked every row. This program opens a missing file and a file that holds OLD in each mode and reports what happened:

خشتەیەک لە کتێبێکدا دەکرێت هەڵە بێت، بۆیە هەموو ڕیزێکمان پشکنی. ئەم نەبوو و کە OLDـی تێدایە بە هەر دۆخێک دەکاتەوە و ڕایدەگەیەنێت چی ڕووی دا:

Every mode, testedهەموو دۆخێک، تاقیکراوەmodes_check.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import os

def try_mode(mode):
    """Open a missing file and an existing file in this mode; report what happens."""
    enc = None if "b" in mode else "utf-8"     # binary modes take no encoding
    # 1. a missing file
    if os.path.exists("test.txt"):
        os.remove("test.txt")
    try:
        with open("test.txt", mode, encoding=enc):
            pass
        creates = "yes"
    except FileNotFoundError:
        creates = "no: FileNotFoundError"
    # 2. an existing file that holds OLD
    with open("test.txt", "w", encoding="utf-8") as f:
        f.write("OLD\n")
    try:
        with open("test.txt", mode, encoding=enc) as f:
            start = f.tell()
        with open("test.txt", encoding="utf-8") as f:
            erased = "yes" if f.read() == "" else "no"
        result = f"erases: {erased:3}  starts at: {'end' if start else 'start'}"
    except FileExistsError:
        result = "FileExistsError (file is there)"
    print(f"{mode:4}  creates: {creates:23}  {result}")

for mode in ["r", "r+", "w", "w+", "a", "a+", "x",
             "rb", "rb+", "wb", "wb+", "ab", "ab+"]:
    try_mode(mode)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

Binary modes take no encoding, so enc is None for them.

دۆخە دووانییەکان وەرناگرن، بۆیە enc بۆ ئەوان Noneـە.

Lineدێڕی 6-14

A missing file: does open() create it or raise FileNotFoundError?

نەبوو: ئایا open() دروستی دەکات یان FileNotFoundError دروست دەکات؟

Lineدێڕی 19-20

tell() gives the position just after opening: 0 means the start.

tell() شوێنەکە ڕاستەوخۆ دوای کردنەوە دەدات: 0 واتە سەرەتا.

Lineدێڕی 21-22

Read the file again: is OLD still there?

دیسان بخوێنەوە: ئایا OLD هێشتا لەوێیە؟

A mode also limits what you may do. Reading from a file opened with w or a, or writing to one opened with r, raises io.UnsupportedOperation:

دۆخ ئەوەش سنووردار دەکات کە بۆت هەیە بیکەیت. خوێندنەوە لە کە بە w یان a کراوەتەوە، یان نووسین لە کە بە r کراوەتەوە، io.UnsupportedOperation دروست دەکات:

What each mode allowsهەر دۆخێک ڕێگە بە چی دەداتmodes_read_write.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
# Which modes allow reading and which allow writing?
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("OLD\n")

for mode in ["r", "w", "a", "r+"]:
    with open("test.txt", mode, encoding="utf-8") as f:
        for name, action in [("read", f.read), ("write", lambda: f.write(""))]:
            try:
                action()
                print(f"{mode:2}: {name} ok")
            except Exception as e:
                print(f"{mode:2}: {name} fails: {type(e).__name__}: {e}")
Quick checkپشکنینی خێراA file is opened with "a+" and the program calls f.read() straight away. What does it get? بە "a+" کراوەتەوە و یەکسەر f.read() بانگ دەکات. چی وەردەگرێت؟

Closing a fileداخستنی فایلێک

When you have finished, close the file with f.close(). Closing does two jobs. It writes out everything that is still waiting in the file's , and it frees the file for other programs. Python does not send every write() to the disk at once: it collects the text in a buffer in memory and writes bigger pieces, which is much faster. You can see it happen:

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

The text waits in a buffer until close()دەقەکە تا ⁦close()⁩ لە بافەردا چاوەڕێ دەکاتbuffer_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import os

f = open("log.txt", "w", encoding="utf-8")
f.write("Shop opened at 8:00\n")
print("Size before close():", os.path.getsize("log.txt"), "bytes")
f.close()
print("Size after close(): ", os.path.getsize("log.txt"), "bytes")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4-5

After write() the file on the disk is still empty: the text is in the buffer.

دوای write() سەر دیسک هێشتا بەتاڵە: دەقەکە لە .

Lineدێڕی 6-7

close() writes the buffer out: now the file has its 20 bytes.

close() دەنووسێت: ئێستا ⁦20⁩ تێدایە.

So if a program crashes, or the power goes off, before the file is closed, the last writes can be lost. There is no error message: the data are simply missing. f.flush() writes the buffer out without closing, for a program that keeps a file open for a long time.

کەواتە ئەگەر بکەوێت یان کارەبا ببڕێت پێش داخستنی ، دوایین نووسینەکان دەکرێت ون ببن. هیچ پەیامێکی نییە: بە سادەیی ون دەبێت. f.flush() دەنووسێت بەبێ داخستن، بۆ کە بۆ کاتێکی درێژ کراوە دەهێڵێتەوە.

Quick checkپشکنینی خێراA program writes to a file but never calls close(), and then crashes. What can happen? لە دەنووسێت بەڵام هەرگیز close() بانگ ناکات، پاشان دەکەوێت. چی دەکرێت ڕوو بدات؟

Closing a fileداخستنی فایلێک

The with statement closes it for youڕستەی with بۆت دایدەخات

Forgetting close() is easy, and an exception between open() and close() skips it. The with statement closes the file for you when its block ends, even when an exception happens inside it. It is the recommended way, and every example from now on uses it.

لەبیرکردنی close() ئاسانە و لە نێوان open() و close()ـدا بازی بەسەردا دەدات. with کاتێک بلۆکەکەی کۆتایی دێت بۆت دادەخات، تەنانەت کاتێک لەناویدا ڕوو دەدات. ئەمە ڕێگا پێشنیارکراوەکەیە و هەموو نموونەیەک لێرە بەدواوە بەکاری دەهێنێت.

with closes the file, even after an errorwith فایلەکە دادەخات، تەنانەت دوای هەڵەیەکwith_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("Shop closed at 22:00\n")
    print("Inside with:  closed?", f.closed)
print("After with:   closed?", f.closed)

try:
    with open("log.txt", "a", encoding="utf-8") as f:
        f.write("Sold: 3 teas\n")
        price = int("five hundred")    # ValueError inside the with block
except ValueError:
    print("After an error: closed?", f.closed)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

with open(...) as f: opens the file and names the file object f.

with open(...) as f: دەکاتەوە و ناوی دەنێت f.

Lineدێڕی 4

The block has ended, so the file is closed.

بلۆکەکە کۆتایی هات، بۆیە داخرا.

Lineدێڕی 9

A ValueError jumps out of the block, but with still closes the file.

ValueErrorـێک لە بلۆکەکە دەردەپەڕێت، بەڵام with هەر دادەخات.

with does the same job as try … finally with close() in the finally block (else and finally), in fewer lines:

with هەمان کاری try … finally دەکات کە close() لە بلۆکی finallyـدایە (else و finally)، بە دێڕی کەمتر:

What with saves you from writingئەوەی with لە نووسینی ڕزگارت دەکاتtry_finally.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
f = open("log.txt", "a", encoding="utf-8")
try:
    f.write("Sold: 2 coffees\n")
finally:
    f.close()                          # runs even if write() fails
print("closed?", f.closed)
Quick checkپشکنینی خێراWhat is f.closed straight after a with open(...) as f: block?ڕاستەوخۆ دوای بلۆکێکی with open(...) as f:، f.closed چییە؟

Writing: write()نووسین: ⁦write()⁩

To write, open the file with w, a, x or a + mode. write() takes one string, writes it and returns the number of characters it wrote. It adds nothing of its own: no space and no newline. Put \n into the string yourself where a line must end, and turn numbers into strings with str().

بۆ نووسین، بە w، a، x یان دۆخێکی + بکەرەوە. write() یەک وەردەگرێت، دەینووسێت و ژمارەی دەگەڕێنێتەوە. هیچ شتێک لە خۆیەوە زیاد ناکات: نە بۆشایی و نە دێڕی نوێ. خۆت \n بخەرە ناو لەو شوێنەی دێڕ دەبێت کۆتایی بێت و ژمارەکان بە str() بکە بە .

write() returns how many characters it wrote⁦write()⁩ دەڵێت چەند نووسەی نووسیwrite_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("stock.txt", "w", encoding="utf-8") as f:
    print(f.write("Tea glasses: "))
    print(f.write(str(48) + "\n"))     # a number must become text first
    print(f.write("پەرداخی چا: 48\n"))

with open("stock.txt", encoding="utf-8") as f:
    print(f.read())
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

13 characters: Tea glasses: (the space counts).

⁦13⁩ : Tea glasses: (بۆشاییەکەش دەژمێردرێت).

Lineدێڕی 3

str(48) turns the number into the text "48"; with \n that is 3 characters.

str(48) ژمارەکە دەکات بە دەقی "48"؛ لەگەڵ \n دەکاتە 3 .

Lineدێڕی 4

15: the count is in characters, not bytes. Each Kurdish letter is one character here.

⁦15⁩: ژماردنەکە بە ، نەک بە . هەر پیتێکی کوردی لێرەدا یەک .

Forget str() and Python stops you:

ئەگەر str() لەبیر بکەیت، ڕێگەت پێ نادات:

write() takes only strings⁦write()⁩ تەنها زنجیرەنووسە وەردەگرێتwrite_int.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("stock.txt", "w", encoding="utf-8") as f:
    f.write(48)
Quick checkپشکنینی خێراWhat does f.write("Hi\n") return?f.write("Hi\n") چی دەگەڕێنێتەوە؟

Writing: write()نووسین: ⁦write()⁩

Many lines at once: writelines()چەند دێڕێک پێکەوە: ⁦writelines()⁩

writelines() writes many strings at once, from a list, a tuple or any other sequence of strings. It is the same as calling write() for each item: it adds no newlines, and it returns None, not a count.

writelines() چەند پێکەوە دەنووسێت، لە ، یان هەر زنجیرەیەکی تری . وەک ئەوەیە بۆ هەر دانەیەک write() بانگ بکەیت: هیچ دێڕێکی نوێ زیاد ناکات و None دەگەڕێنێتەوە، نەک ژمارە.

Three cities, three linesسێ شار، سێ دێڕwritelines_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
cities = ["Erbil\n", "Sulaymaniyah\n", "Duhok\n"]
with open("cities.txt", "w", encoding="utf-8") as f:
    f.writelines(cities)

with open("cities.txt", encoding="utf-8") as f:
    print(f.read())
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Every string ends with \n, so every city gets its own line.

هەموو بە \n کۆتایی دێت، بۆیە هەر شارێک دێڕی خۆی هەیە.

Without the \n the cities run together: writelines(["Erbil", "Sulaymaniyah", "Duhok"]) writes ErbilSulaymaniyahDuhok on one line. The textbook also asks two questions. Can writelines() take a tuple of numbers? No, every item must be a string:

بەبێ \n شارەکان دەچنە ناو یەکتر: writelines(["Erbil", "Sulaymaniyah", "Duhok"]) ErbilSulaymaniyahDuhok لە یەک دێڕدا دەنووسێت. کتێبەکە دوو پرسیاری تریش دەکات. ئایا writelines() دەتوانێت ژمارە وەربگرێت؟ نەخێر، دەبێت هەموو دانەیەک بێت:

A tuple of numbersتاپڵێک ژمارەwritelines_numbers.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("prices.txt", "w", encoding="utf-8") as f:
    f.writelines((500, 750, 1000))      # a tuple of numbers

And can write() take the whole list instead? Also no: f.write(["Erbil\n", "Duhok\n"]) raises TypeError: write() argument must be str, not list. To save numbers, turn each one into a line of text yourself:

ئایا write() دەتوانێت هەموو وەربگرێت؟ ئەویش نەخێر: f.write(["Erbil\n", "Duhok\n"]) TypeError: write() argument must be str, not list دروست دەکات. بۆ هەڵگرتنی ژمارەکان، خۆت هەر یەکێکیان بکە بە دێڕێکی دەق:

Numbers saved one per lineژمارەکان، هەر یەکەیان لە دێڕێکداprices_lines.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
prices = (500, 750, 1000)
with open("prices.txt", "w", encoding="utf-8") as f:
    for p in prices:
        f.write(str(p) + "\n")         # each number becomes one line of text

with open("prices.txt", encoding="utf-8") as f:
    print(f.read(), end="")
Quick checkپشکنینی خێراf.writelines(["tea", "coffee"]) writes what?f.writelines(["tea", "coffee"]) چی دەنووسێت؟

Writing: write()نووسین: ⁦write()⁩

Append or write? a versus wزیادکردن یان نووسین؟ a بەرامبەر w

Mode a (append) writes at the end and keeps everything that is already there. Mode w starts again from an empty file every time. Here are two small programs, each run twice. The first appends:

دۆخی a (زیادکردن) لە کۆتاییدا دەنووسێت و هەموو ئەوەی پێشتر هەیە دەیهێڵێتەوە. دۆخی w هەر جارێک لە بەتاڵەوە دەست پێ دەکاتەوە. ئەمە دوو بچووکن، هەر یەکەیان دوو جار کاری پێکراوە. یەکەمیان زیاد دەکات:

Mode a: the visitors add upدۆخی a: سەردانکەران کۆ دەبنەوەvisitors_append.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("visitors.txt", "a", encoding="utf-8") as f:
    f.write("Dilan\n")

with open("visitors.txt", encoding="utf-8") as f:
    print(f.read(), end="")

The second is the same program with "w" in line 1. The second run erased the first visitor:

دووەمیان هەمان بە "w" لە دێڕی 1ـدا. جاری دووەم یەکەم سەردانکەری سڕییەوە:

Mode w: only the last visitor is leftدۆخی w: تەنها دوایین سەردانکەر دەمێنێتvisitors_write.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("visitors.txt", "w", encoding="utf-8") as f:
    f.write("Dilan\n")

with open("visitors.txt", encoding="utf-8") as f:
    print(f.read(), end="")
Quick checkپشکنینی خێراA program should keep a record of every visit for a whole month. Which mode should it open the log with? دەبێت تۆماری هەموو سەردانێک بۆ مانگێکی تەواو بهێڵێتەوە. بە کام دۆخ بکاتەوە؟

Python File Handling for BeginnersDave Gray · Englishئینگلیزی · 135K viewsبینین · 3K likesلایک · Partبەشی 8:43–13:36 (ofلە 22:40)

Mode a adds to the end of a file and keeps the old lines; mode w empties the file first and writes again.

a دەقی نوێ دەخاتە کۆتایی و دێڕە کۆنەکان دەپارێزێت؛ w سەرەتا بەتاڵ دەکات و پاشان دەنووسێت.

Watch 8:43–13:36: appending with "a", then writing and overwriting with "w".

لە ⁦8:43⁩ تا ⁦13:36⁩ سەیر بکە: زیادکردن بۆ کۆتایی بە "a"، پاشان نووسین و نووسینەوە بەسەر ناوەڕۆکی کۆندا بە "w".

Reading: read()خوێندنەوە: ⁦read()⁩

To read, open the file in a mode that reads: r (the default), r+, w+ or a+. The reading examples use this small file of marks, marks.txt:

بۆ خوێندنەوە، بە دۆخێک بکەرەوە کە دەخوێنێتەوە: r (بنەڕەت)، r+، w+ یان a+. نموونەکانی خوێندنەوە ئەم بچووکەی نمرە بەکار دەهێنن، marks.txt:

marks.txtفایلی ⁦marks.txt⁩
Aram 17
Shilan 19
Karwan 15

read(n) reads the next n characters; read() with no number reads everything that is left as one string. At the end of the file it returns the empty string ''. (repr() shows the hidden \n characters.)

read(n) n داهاتوو دەخوێنێتەوە؛ read() بەبێ ژمارە هەموو پاشماوەکە وەک یەک دەخوێنێتەوە. لە کۆتایی بەتاڵ '' دەگەڕێنێتەوە. (repr() شاراوەی \n پیشان دەدات.)

read(n) and read()⁦read(n)⁩ و ⁦read()⁩read_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as f:
    print(repr(f.read(4)))     # 4 characters
    print(repr(f.read(3)))     # the next 3
    print(repr(f.read()))      # everything that is left
    print(repr(f.read()))      # nothing is left
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-3

Each call continues where the last one stopped.

هەر بانگکردنێک لەو شوێنەوە بەردەوام دەبێت کە پێشووەکە وەستا.

Lineدێڕی 5

Nothing is left: ''.

هیچی تر نییە: ''.

Quick checkپشکنینی خێراA program opens marks.txt, calls f.read(4) and f.read(3). What does a third call f.read(1) return? marks.txt دەکاتەوە و f.read(4) و f.read(3) بانگ دەکات. بانگکردنی سێیەم f.read(1) چی دەگەڕێنێتەوە؟

22- خوێندنه وه ی فایل Reading FilesMR. Ant · Kurdish (Sorani)کوردی (سۆرانی) · 4.6K viewsبینین · 165 likesلایک

A Kurdish (Sorani) lesson on opening a file in Python and reading its content.

وانەیەکی کوردی (سۆرانی) دەربارەی کردنەوەی لە و خوێندنەوەی ناوەڕۆکەکەی.

Kurdish (Sorani) video, 10 minutes: reading files in Python (MR. Ant Python course, part 22).

ڤیدیۆیەکی کوردی (سۆرانی)، ⁦10⁩ خولەک: خوێندنەوەی لە (کۆرسی ⁦MR. Ant⁩، بەشی ⁦22⁩).

Reading: read()خوێندنەوە: ⁦read()⁩

One line at a time: readline()یەک دێڕ لە هەر جارێکدا: ⁦readline()⁩

readline() reads one line, including its \n. Each call continues where the last one stopped. At the end of the file it returns '': an empty string, not an error. A blank line in the middle of a file comes back as '\n', so '' can only mean the end.

readline() یەک دێڕ دەخوێنێتەوە، لەگەڵ \nـەکەی. هەر بانگکردنێک لەو شوێنەوە بەردەوام دەبێت کە پێشووەکە وەستا. لە کۆتایی '' دەگەڕێنێتەوە: بەتاڵ، نەک . دێڕێکی بەتاڵ لە ناوەڕاستی وەک '\n' دەگەڕێتەوە، بۆیە '' تەنها دەتوانێت مانای کۆتایی بێت.

readline() four timesچوار جار ⁦readline()⁩readline_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as f:
    print(repr(f.readline()))
    print(repr(f.readline()))
    print(repr(f.readline()))
    print(repr(f.readline()))  # at the end of the file

readline(n) reads at most n characters, and never past the end of the line: readline(4) gives 'Aram', the next readline() gives the rest of that line, ' 17\n'. To read a whole file with readline(), repeat it in a loop that stops at '':

readline(n) زۆرترین n دەخوێنێتەوە و هەرگیز لە کۆتایی دێڕەکە تێناپەڕێت: readline(4) 'Aram' دەدات، readline()ـی دواتر پاشماوەی هەمان دێڕ دەدات، ' 17\n'. بۆ خوێندنەوەی هەموو بە readline()، لە دووبارەی بکەرەوە کە لە ''ـدا دەوەستێت:

Read every line with readline()هەموو دێڕێک بە ⁦readline()⁩ بخوێنەوەreadline_loop.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as f:
    line = f.readline()
    while line != "":          # '' means: end of the file
        print(line, end="")    # the line already ends with \n
        line = f.readline()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

Stop at '', the end of the file.

لە ''ـدا بوەستە، کۆتایی .

Lineدێڕی 4

end="": the line already has its own \n.

end="": دێڕەکە خۆی \nـی هەیە.

Lineدێڕی 5

Read the next line before the test runs again. Forget this line and the loop never ends.

پێش ئەوەی تاقیکردنەوەکە دووبارە بێتەوە دێڕی داهاتوو بخوێنەوە. ئەم دێڕە لەبیر بکەیت، هەرگیز کۆتایی نایەت.

Quick checkپشکنینی خێراWhen does f.readline() return ''?f.readline() کەی '' دەگەڕێنێتەوە؟

Reading: read()خوێندنەوە: ⁦read()⁩

All lines: readlines() and the for loopهەموو دێڕەکان: ⁦readlines()⁩ و خولی for

readlines() reads all the lines into a list of strings. Each string still ends with \n:

readlines() هەموو دێڕەکان دەخوێنێتەوە بۆ ناو لە . هەر هێشتا بە \n کۆتایی دێت:

readlines() gives a list⁦readlines()⁩ لیستێک دەداتreadlines_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as f:
    lines = f.readlines()
print(lines)
print(len(lines), "lines")

The best way for most programs is a for loop over the file object itself. It reads one line on each turn, uses little memory even for a huge file and needs no '' test:

باشترین ڕێگا بۆ زۆربەی بەسەر خودی . لە هەر خولانەوەیەکدا یەک دێڕ دەخوێنێتەوە، تەنانەت بۆ زۆر گەورەش کەم بەکار دەهێنێت و پێویستی بە تاقیکردنەوەی '' نییە:

The usual way: for line in fڕێگا ئاساییەکە: ⁦for line in f⁩for_line.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as f:
    for line in f:
        line = line.rstrip("\n")   # remove the newline at the end
        print(line)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

Each turn of the loop gets the next line, with its \n.

هەر خولانەوەیەکی دێڕی داهاتوو وەردەگرێت، لەگەڵ \nـەکەی.

Lineدێڕی 3

rstrip("\n") removes only the newline at the end.

rstrip("\n") تەنها دێڕی نوێی کۆتایی لادەبات.

WayڕێگاGivesچی دەداتUse it whenکەی بەکاری بهێنە
f.read()the whole file as one stringهەموو وەک یەک the file is small and you need it all at once بچووکە و هەمووت پێکەوە پێویستە
f.readline()the next line, '' at the endدێڕی داهاتوو، لە کۆتاییدا ''you need one line, for example a headerیەک دێڕت پێویستە، بۆ نموونە سەردێڕێک
f.readlines()a list of all lines لە هەموو دێڕەکانyou need the lines by index, or to count themدێڕەکانت بە پێویستە، یان بۆ ژماردنیان
for line in f:one line per turnیەک دێڕ لە هەر خولانەوەیەکداalmost always: simple, and good for big filesنزیکەی هەمیشە: سادەیە و بۆ گەورە باشە
Quick checkپشکنینی خێراWhich way reads a file line by line with the least code and little memory?کام ڕێگا دێڕ بە دێڕ بە کەمترین کۆد و کەم دەخوێنێتەوە؟

Reading: read()خوێندنەوە: ⁦read()⁩

Words, numbers and CSV tablesوشە، ژمارە و خشتەی CSV

A line is a string, so every string method works on it. split() cuts a line into words (split() and join()), and the newline disappears with the spaces. splitlines() gives the line without its \n, in a one-item list:

دێڕ ، بۆیە هەموو لەسەری کار دەکات. split() دێڕێک دەکات بە وشە (⁦split()⁩ و ⁦join()⁩) و دێڕە نوێکە لەگەڵ بۆشاییەکان لادەچێت. splitlines() دێڕەکە بەبێ \nـەکەی دەدات، لە یەک دانەییدا:

Words from each lineوشەکانی هەر دێڕێکwords_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as f:
    for line in f:
        words = line.split()       # split at spaces; \n goes too
        print(words)

with open("marks.txt", encoding="utf-8") as f:
    for line in f:
        print(line.splitlines())   # one item: the line without \n

Everything read from a text file is text. To calculate with it, convert it: int("17") is the number 17.

هەموو ئەوەی لە دەخوێنرێتەوە دەقە. بۆ ژماردن پێی، بیگۆڕە: int("17") ژمارە ⁦17⁩ـە.

Adding up the marksکۆکردنەوەی نمرەکانmarks_sum.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
total = 0
with open("marks.txt", encoding="utf-8") as f:
    for line in f:
        name, mark = line.split()
        total = total + int(mark)  # the text "17" becomes the number 17
print("Total:", total)

A CSV file (comma-separated values) is a text file that holds a table: one row on each line, the values separated by commas. Spreadsheet programs open and save it. Read it into a list of lists, one inner list for each row (Lists inside a list). Here is marks.csv:

CSV ⁦(comma-separated values)⁩ کە خشتەیەک هەڵدەگرێت: هەر ڕیزێک لە دێڕێکدا و بە کۆما جیا کراونەتەوە. دەیکەنەوە و هەڵی دەگرن. بیخوێنەوە بۆ ناو لە ، بۆ هەر ڕیزێک ناوەکی (لیستە دووڕەهەندەکان). ئەمە marks.csvـە:

marks.csvفایلی ⁦marks.csv⁩
name,maths,physics
Aram,17,15
Shilan,19,18
Karwan,15,16
A CSV table into a list of listsخشتەیەکی CSV بۆ ناو لیستێک لە لیستەکانcsv_marks.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
table = []
with open("marks.csv", encoding="utf-8") as f:
    header = f.readline().rstrip("\n").split(",")
    for line in f:
        name, maths, physics = line.rstrip("\n").split(",")
        table.append([name, int(maths), int(physics)])

print(header)
print(table)
for name, maths, physics in table:
    print(f"{name:8} average {(maths + physics) / 2}")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

The first line is the header: the column names.

یەکەم دێڕ سەردێڕەکەیە: ناوی ستوونەکان.

Lineدێڕی 5-6

Split at the commas and turn the marks into numbers.

لە کۆماکاندا لەتی بکە و نمرەکان بکە بە ژمارە.

Quick checkپشکنینی خێراA line read from a file is 'Karwan 15\n'. What does line.split() give?دێڕێکی خوێندراوە لە 'Karwan 15\n'ـە. line.split() چی دەدات؟

A complete program: save, then filterبەرنامەیەکی تەواو: هەڵگرتن، پاشان پاڵاوتن

Now everything together. The user types sentences until they type END. The program saves them in a file, one per line, then reads the file back and shows only the sentences that begin with a capital letter.

ئێستا هەموو شتێک پێکەوە. ڕستە دەنووسێت تا END دەنووسێت. لە هەڵیان دەگرێت، هەر یەکەیان لە دێڕێکدا، پاشان دەخوێنێتەوە و تەنها ئەو ڕستانە پیشان دەدات کە بە پیتی گەورە دەست پێ دەکەن.

The planپلانەکە
  1. Open for writingکردنەوە بۆ نووسین

    Open sentences.txt with "w" (a new, empty file).

    sentences.txt بە "w" بکەرەوە ( نوێی بەتاڵ).

  2. Save until ENDهەڵگرتن تا END

    Repeat: read a sentence; stop at END; otherwise write it with \n.

    دووبارە بکەرەوە: ڕستەیەک بخوێنەوە؛ لە ENDـدا بوەستە؛ ئەگینا لەگەڵ \n بینووسە.

  3. Read backخوێندنەوە

    Close it, open it again for reading and walk through the lines.

    دایبخە، دیسان بۆ خوێندنەوە بیکەرەوە و بە دێڕەکاندا بڕۆ.

  4. Filterپاڵاوتن

    Print a line only if its first character is a capital letter.

    دێڕێک تەنها کاتێک چاپ بکە کە یەکەم پیتێکی گەورە بێت.

Save sentences, then show the ones with a capitalڕستەکان هەڵبگرە، پاشان ئەوانەی پیتی گەورەیان هەیە پیشان بدەcapital_lines.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("sentences.txt", "w", encoding="utf-8") as f:
    while True:
        line = input("Type a sentence (END to stop): ")
        if line == "END":
            break
        f.write(line + "\n")

print("Sentences that start with a capital letter:")
with open("sentences.txt", encoding="utf-8") as f:
    for line in f:
        line = line.rstrip("\n")
        if line != "" and line[0].isupper():
            print(line)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-6

The with block keeps the file open while the loop writes; it closes when the loop ends.

بلۆکی with کراوە دەهێڵێتەوە تا دەنووسێت؛ کاتێک کۆتایی هات دادەخرێت.

Lineدێڕی 6

input() gives no newline, so add \n yourself.

input() دێڕی نوێ نادات، بۆیە خۆت \n زیاد بکە.

Lineدێڕی 12

line != "" protects line[0]: an empty line has no first character.

line != "" line[0] دەپارێزێت: دێڕی بەتاڵ هیچ یەکەمی نییە.

The Kurdish sentence was saved but not shown. Arabic-script letters have no capital and small forms, so "ک".isupper() is False, and so is "ک".islower() (More case methods).

ڕستە کوردییەکە هەڵگیرا بەڵام پیشان نەدرا. پیتەکانی ئەلفوبێی عەرەبی شێوەی گەورە و بچووکیان نییە، بۆیە "ک".isupper() Falseـە و "ک".islower()ـیش هەروەها (پیتی گەورە و بچووک).

Quick checkپشکنینی خێراIn the program above, why is the test line != "" needed before line[0]?لە سەرەوەدا، بۆچی تاقیکردنەوەی line != "" پێش line[0] پێویستە؟

Errors you will meetچەند هەڵەیەک کە تووشیان دەبیت

Files live outside your program, so many things can go wrong that your code cannot prevent: the file was deleted, the name is misspelt, the name belongs to a folder, or another user owns the file. Python raises an exception for each case, and they are all kinds of OSError:

لە دەرەوەی دەژین، بۆیە زۆر شت دەکرێت هەڵە بچێت کە کۆدەکەت ناتوانێت ڕێگری لێ بکات: سڕاوەتەوە، ناوەکە بە هەڵە نووسراوە، ناوەکە هی یان تر خاوەنی . بۆ هەر حاڵەتێک دروست دەکات و هەموویان جۆرێکن لە OSError:

Four ways open() can failچوار ڕێگا کە ⁦open()⁩ تێیاندا سەرناکەوێتfile_errors.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
tests = [("missing.txt", "r"),   # the file is not there
         ("data", "r"),          # data is a folder, not a file
         ("marks.txt", "x"),     # x must create a NEW file
         ("secret.txt", "r")]    # we have no right to read it

for name, mode in tests:
    try:
        with open(name, mode, encoding="utf-8") as f:
            print(f.read())
    except OSError as e:
        print(type(e).__name__, "-", e)

print(IOError is OSError)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 10

except OSError catches all four, because they are all kinds of OSError.

except OSError هەر چواریان دەگرێت، چونکە هەموویان جۆرێکن لە OSError.

Lineدێڕی 13

IOError is just another name for OSError.

IOError تەنها ناوێکی ترە بۆ OSError.

ExceptionWhenکەی
FileNotFoundErrorreading a file that does not exist, or a folder in the path is missingخوێندنەوەی کە بوونی نییە، یان لە نییە
FileExistsErrormode x, but the file is already thereدۆخی x، بەڵام پێشتر هەیە
IsADirectoryErrorthe name is a folder (Windows says PermissionError here)ناوەکە (Windows لێرەدا دەڵێت PermissionError)
PermissionErrorno right to read or write the file, for example a protected system fileمافی خوێندنەوە یان نووسینی نییە، بۆ نموونە پارێزراوی سیستەم
UnicodeDecodeErrorthe bytes do not fit the encoding: a binary file opened as text, or a wrong encoding لەگەڵ ناگونجێن: وەک دەق کراوەتەوە، یان هەڵە
ValueErrorreading or writing a closed file: I/O operation on closed fileخوێندنەوە یان نووسینی داخراو: I/O operation on closed file
io.UnsupportedOperationreading in w or a, writing in r, a relative seek in text modeخوێندنەوە لە w یان a، نووسین لە r، seekـی ڕێژەیی لە دۆخی دەقدا
Quick checkپشکنینی خێراWhich exception do you get when a program opens report.txt with "x" and the file already exists?کاتێک report.txt بە "x" دەکاتەوە و پێشتر هەیە، کام وەردەگریت؟

Errors you will meetچەند هەڵەیەک کە تووشیان دەبیت

Catching file errorsگرتنی هەڵەکانی فایل

Catch the error you expect with try and except (Catch the exceptions you expect) and the program can ask again instead of crashing:

ئەو چاوەڕێی دەکەیت بە try و except بگرە (هەڵاوێردەکانی چاوەڕوانکراو بگرە) و دەتوانێت دیسان بپرسێت لەبری ئەوەی بکەوێت:

Ask until the file opensبپرسە تا فایلەکە دەکرێتەوەask_filename.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
while True:
    name = input("File to show: ")
    try:
        with open(name, encoding="utf-8") as f:
            print(f.read(), end="")
        break                          # it worked: stop asking
    except FileNotFoundError:
        print("There is no file called", name)
    except IsADirectoryError:
        print(name, "is a folder, not a file")
    except PermissionError:
        print("You may not read", name)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6

break only runs when the file was opened and shown.

break تەنها کاتێک جێبەجێ دەبێت کە کرابێتەوە و پیشان درابێت.

Lineدێڕی 7-12

One except for each problem the user can cause. (On Windows a folder name gives PermissionError, so it is caught too.)

یەک except بۆ هەر کێشەیەک کە دەتوانێت دروستی بکات. (لە Windowsـدا ناوی PermissionError دەدات، بۆیە ئەویش دەگیرێت.)

One more error: a file closed by with cannot be read after the block. Indent the reading lines inside the with block, or Python raises ValueError: I/O operation on closed file.

تر: کە with دایخستووە دوای بلۆکەکە ناخوێنرێتەوە. دێڕەکانی خوێندنەوە لەناو بلۆکی withـدا بە بۆشایی بخەرە ژوورەوە، ئەگینا ValueError: I/O operation on closed file. دروست دەکات.

Quick checkپشکنینی خێراIn the program above, why is break inside the try block, after the with block?لە سەرەوەدا، بۆچی break لەناو بلۆکی tryـدا و دوای بلۆکی with هاتووە؟

Read files using Python! 🔍Bro Code · Englishئینگلیزی · 49K viewsبینین · 1K likesلایک · Partبەشی 2:26–4:12 (ofلە 6:56)

Reading a file inside try and except: catching FileNotFoundError and PermissionError so the program does not crash.

خوێندنەوەی لەناو try و except: گرتنی FileNotFoundError و PermissionError تا تێک نەچێت.

Watch 2:26–4:12: catching FileNotFoundError and PermissionError when a file is opened.

لە ⁦2:26⁩ تا ⁦4:12⁩ سەیر بکە: گرتنی FileNotFoundError و PermissionError کاتێک دەکرێتەوە.

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

MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
Opening an important file with "w"کردنەوەی گرنگ بە "w"its content is erased at onceناوەڕۆکەکەی یەکسەر دەسڕدرێتەوە"a" to add, "r" to read, "x" for a new file"a" بۆ زیادکردن، "r" بۆ خوێندنەوە، "x" بۆ نوێ
No encoding= for a text fileنەبوونی encoding= بۆ Kurdish text breaks on another computer (UnicodeDecodeError or nonsense)دەقی کوردی لەسەر تر تێک دەچێت (UnicodeDecodeError یان شتی بێمانا)encoding="utf-8"
A readline() loop that never reads the next line, or never tests for '' readline() کە هەرگیز دێڕی داهاتوو ناخوێنێتەوە، یان هەرگیز '' تاقی ناکاتەوەan for line in f:for line in f:
Forgetting close()لەبیرکردنی close()the last writes may never reach the diskلەوانەیە دوایین نووسینەکان هەرگیز نەگەنە دیسکwith open(...) as f:with open(...) as f:
print(line) for lines read from a fileprint(line) بۆ ئەو دێڕانەی لە خوێندراونەتەوەan empty line after every lineدێڕێکی بەتاڵ دوای هەموو دێڕێکline.rstrip("\n") or print(line, end="")line.rstrip("\n") یان print(line, end="")
f.write(48) or writelines() with numbersf.write(48) یان writelines() بە ژمارەTypeError: write() argument must be str, not intf.write(str(48) + "\n")f.write(str(48) + "\n")
writelines() without \n in the stringswritelines() بەبێ \n لە all the lines run togetherهەموو دێڕەکان دەچنە ناو یەکترend every string with \nهەموو بە \n کۆتایی پێ بهێنە
Opening a picture or another binary file as textکردنەوەی وێنەیەک یان هەر وەک دەقUnicodeDecodeError"rb" for every binary file"rb" بۆ هەموو
Reading the file after the with blockخوێندنەوەی دوای بلۆکی withValueError: I/O operation on closed file.indent the reading lines inside the blockدێڕەکانی خوێندنەوە بخەرە ناو بلۆکەکە

Exercises: explain and chooseڕاهێنانەکان: ڕوونکردنەوە و هەڵبژاردن

ExerciseڕاهێنانTell them apartجیایان بکەرەوە

Explain the difference between: (a) a text file and a binary file; (b) readline() and readlines(); (c) write() and writelines().

جیاوازیی نێوان ئەمانە ڕوون بکەرەوە: (أ) و ؛ (ب) readline() و readlines()؛ (ج) write() و writelines().

Show answerوەڵامەکە پیشان بدە
PairجووتDifferenceجیاوازی
text / binary file / A text file holds character codes in lines ending with \n and opens in any text editor. A binary file holds other bytes (pictures, sound, programs) and needs the right program; open it with b in the mode. کۆدی لە دێڕدا هەڵدەگرێت کە بە \n کۆتایی دێن و لە هەر دەکرێتەوە. تر هەڵدەگرێت (وێنە، دەنگ، ) و گونجاوی پێویستە؛ بە b لە دۆخەکەدا بیکەرەوە.
readline() / readlines()readline() returns the next single line as a string ('' at the end); readlines() returns all the lines at once as a list of strings.readline() تەنها دێڕی داهاتوو وەک دەگەڕێنێتەوە (لە کۆتاییدا '')؛ readlines() هەموو دێڕەکان پێکەوە وەک لە دەگەڕێنێتەوە.
write() / writelines()write() writes one string and returns the number of characters; writelines() writes every string of a list or tuple and returns None. Neither adds newlines.write() یەک دەنووسێت و ژمارەی دەگەڕێنێتەوە؛ writelines() هەموو یان دەنووسێت و None دەگەڕێنێتەوە. هیچیان دێڕی نوێ زیاد ناکەن.
ExerciseڕاهێنانChoose the modeدۆخەکە هەڵبژێرە

Write the mode and the open() statement for: (a) a text file diary.txt for reading and writing, keeping its content; (b) a binary file scores.dat for writing; (c) a text file log.txt for appending and reading; (d) a binary file photo.png, read only.

دۆخەکە و open() بنووسە بۆ: (أ) diary.txt بۆ خوێندنەوە و نووسین، بە هێشتنەوەی ناوەڕۆکەکەی؛ (ب) scores.dat بۆ نووسین؛ (ج) log.txt بۆ زیادکردن و خوێندنەوە؛ (د) photo.png، .

Show answerوەڵامەکە پیشان بدە
PYTHONType in a terminalلە تێرمیناڵدا بینووسە
diary = open("diary.txt", "r+", encoding="utf-8")   # (a) must exist; nothing erased
scores = open("scores.dat", "wb")                     # (b) created or erased
log = open("log.txt", "a+", encoding="utf-8")         # (c) writes go to the end
photo = open("photo.png", "rb")                       # (d) bytes, no encoding

For (a), "w+" would also read and write, but it erases the diary first.

بۆ (أ)، "w+"یش دەخوێنێتەوە و دەنووسێت، بەڵام سەرەتا دەفتەری ڕۆژانەکە دەسڕێتەوە.

ExerciseڕاهێنانWhy close a file?بۆچی فایلێک دابخەین؟

Why should a program close a file when it has finished? What happens if it does not; does Python show an error? And what is the difference between (a) P = open("notes.txt", encoding="utf-8") then P.read(10), and (b) with open("notes.txt", encoding="utf-8") as P: then x = P.read()?

بۆچی دەبێت کاتێک تەواو بوو دابخات؟ ئەگەر دای نەخات چی ڕوو دەدات؛ ئایا پیشان دەدات؟ هەروەها جیاوازیی نێوان (أ) P = open("notes.txt", encoding="utf-8") پاشان P.read(10) و (ب) with open("notes.txt", encoding="utf-8") as P: پاشان x = P.read() چییە؟

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

Closing writes out the buffer and frees the file. Without it there is no error message, but the last writes may be lost if the program crashes, and the file stays locked or open until Python cleans up. (a) reads only the first 10 characters and leaves the file open; nothing keeps the result. (b) reads the whole file into x, and with closes the file when the block ends, even after an error.

داخستن دەنووسێت و ئازاد دەکات. بەبێ ئەوە هیچ پەیامێکی نییە، بەڵام ئەگەر بکەوێت لەوانەیە دوایین نووسینەکان ون ببن و تا پاکی دەکاتەوە کراوە دەمێنێتەوە. (أ) تەنها ⁦10⁩ یەکەم دەخوێنێتەوە و کراوە جێ دەهێڵێت؛ هیچ شتێک ئەنجامەکە هەڵناگرێت. (ب) هەموو دەخوێنێتەوە بۆ ناو x و with کاتێک بلۆکەکە کۆتایی دێت دادەخات، تەنانەت دوای .

Exercises: explain and chooseڕاهێنانەکان: ڕوونکردنەوە و هەڵبژاردن

Exercises: programsڕاهێنانەکان: بەرنامەکان

ExerciseڕاهێنانAppend three lines, then read themسێ دێڕ زیاد بکە، پاشان بیانخوێنەوە

hello.txt already holds the line Hello!. (1) Open it in append mode and add the lines Welcome to our class, Here we learn and play and Tea is at ten o'clock. (2) Write a second program that opens it for reading and shows its content. (3) What would be different if the first program had used "w" instead of "a"?

hello.txt پێشتر دێڕی Hello!ـی تێدایە. ⁦(1)⁩ بە دۆخی زیادکردن بیکەرەوە و دێڕەکانی Welcome to our class، Here we learn and play و Tea is at ten o'clock زیاد بکە. ⁦(2)⁩ دووەم بنووسە کە بۆ خوێندنەوە دەیکاتەوە و ناوەڕۆکەکەی پیشان دەدات. ⁦(3)⁩ ئەگەر یەکەم لەبری "a" "w"ـی بەکار هێنابا چی جیاواز دەبوو؟

Show answerوەڵامەکە پیشان بدە
hello_append.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
lines = ["Welcome to our class\n",
         "Here we learn and play\n",
         "Tea is at ten o'clock\n"]
with open("hello.txt", "a", encoding="utf-8") as f:
    f.writelines(lines)
hello_show.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("hello.txt", encoding="utf-8") as f:
    print(f.read(), end="")

With "w" the file would be emptied first: Hello! would be gone and only the three new lines would be left.

بە "w" سەرەتا بەتاڵ دەکرایەوە: Hello! نەدەما و تەنها سێ دێڕە نوێکە دەمانەوە.

ExerciseڕاهێنانCopy the good marksنمرە باشەکان کۆپی بکە

Read marks.txt (one name and one mark on each line) and write the lines of the students with 17 or more into a new file good.txt. Then show good.txt.

marks.txt بخوێنەوە (هەر دێڕێک یەک ناو و یەک نمرە) و دێڕی ئەو قوتابیانەی ⁦17⁩ یان زیاتریان هەیە لە نوێی good.txtـدا بنووسە. پاشان good.txt پیشان بدە.

Hintئاماژە

name, mark = line.split() and int(mark) >= 17.

name, mark = line.split() و int(mark) >= 17.

Show answerوەڵامەکە پیشان بدە
good_marks.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
with open("marks.txt", encoding="utf-8") as source, \
     open("good.txt", "w", encoding="utf-8") as good:
    for line in source:
        name, mark = line.split()
        if int(mark) >= 17:
            good.write(line)           # the line already ends with \n

with open("good.txt", encoding="utf-8") as f:
    print(f.read(), end="")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-2

Two files in one with: one to read, one to write.

دوو لە یەک withـدا: یەکێک بۆ خوێندنەوە و یەکێک بۆ نووسین.

ExerciseڕاهێنانChallenge: a restaurant's ordersڕاهێنانی قورستر: داواکارییەکانی چێشتخانەیەک

A restaurant wants its orders kept in a file. Each order gets a number that starts again at 1 every day; each line of the file holds the date, the order number, the item code, the quantity and the amount. At closing time the manager wants a summary of the day: how much of each item was sold and the total in IQD. Write save_order(day, lines) and daily_summary(day). (In a full project you would add a menu the manager can change, logins for staff and customers, and a way to delete an order.)

چێشتخانەیەک دەیەوێت داواکارییەکانی لە هەڵبگیرێن. هەر داواکارییەک ژمارەیەک وەردەگرێت کە هەموو ڕۆژێک دیسان لە 1ـەوە دەست پێ دەکاتەوە؛ هەر دێڕێکی بەروار، ژمارەی داواکاری، کۆدی خواردن، ژمارە و بڕی پارە هەڵدەگرێت. لە کاتی داخستندا بەڕێوەبەر پوختەی ڕۆژەکەی دەوێت: لە هەر خواردنێک چەند فرۆشرا و کۆی گشتی بە IQD. save_order(day, lines) و daily_summary(day) بنووسە. (لە پڕۆژەیەکی تەواودا مێنیوێکی خواردن زیاد دەکەیت کە بەڕێوەبەر دەتوانێت بیگۆڕێت، بۆ کارمەندان و کڕیاران و ڕێگایەک بۆ سڕینەوەی داواکارییەک.)

Hintئاماژە

Store one line per item: day,number,code,quantity,amount. split(",") takes it apart again.

بۆ هەر خواردنێک یەک دێڕ هەڵبگرە: day,number,code,quantity,amount. split(",") دیسان لێکی دەکاتەوە.

Show answerوەڵامەکە پیشان بدە
restaurant.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
MENU = {1: ("Kebab", 6000), 2: ("Dolma", 5000), 3: ("Tea", 500)}

def next_order_number(day):
    """Order numbers start again at 1 every day."""
    last = 0
    try:
        with open("orders.txt", encoding="utf-8") as f:
            for line in f:
                date, number = line.split(",")[:2]
                if date == day:
                    last = int(number)
    except FileNotFoundError:
        pass                           # no orders saved yet
    return last + 1

def save_order(day, lines):
    """lines: a list of (item code, quantity). One file line per item."""
    number = next_order_number(day)
    bill = 0
    with open("orders.txt", "a", encoding="utf-8") as f:
        for code, quantity in lines:
            name, price = MENU[code]
            amount = quantity * price
            bill += amount
            f.write(f"{day},{number},{code},{quantity},{amount}\n")
    print(f"Order {number} on {day}: {bill} IQD")

def daily_summary(day):
    sold = {}                          # item name -> quantity
    total = 0
    with open("orders.txt", encoding="utf-8") as f:
        for line in f:
            date, number, code, quantity, amount = line.rstrip("\n").split(",")
            if date == day:
                name = MENU[int(code)][0]
                sold[name] = sold.get(name, 0) + int(quantity)
                total += int(amount)
    print("Summary for", day)
    for name, quantity in sold.items():
        print(f"  {name:6} {quantity}")
    print("  Total:", total, "IQD")

save_order("2026-10-24", [(1, 2), (3, 2)])
save_order("2026-10-24", [(2, 1), (3, 1)])
save_order("2026-10-25", [(3, 4)])     # a new day: number 1 again
daily_summary("2026-10-24")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3-14

Find the last number used today; no file yet means no orders yet.

دوایین ژمارەی ئەمڕۆ بەکارهاتوو بدۆزەوە؛ نەبوونی واتە هێشتا هیچ داواکارییەک نییە.

Lineدێڕی 20-25

Mode a: every order is added after the earlier ones.

دۆخی a: هەر داواکارییەک دوای پێشووەکان زیاد دەکرێت.

Lineدێڕی 31-37

Read every line, keep only today's, and add up the quantities and amounts.

هەموو دێڕێک بخوێنەوە، تەنها هی ئەمڕۆ بهێڵەرەوە و ژمارە و بڕی پارەکان کۆ بکەرەوە.

Summaryپوختە

  • Variables vanish when a program ends; a file on secondary storage keeps data.
  • Text files hold character codes in lines ending with \n; binary files hold other bytes. Open text files with encoding="utf-8", binary files with b.
  • open(name, mode) returns a file object. Modes: r read (missing file = error), w write (erases), a append (at the end), x new file only, + read and write.
  • with open(...) as f: closes the file for you, even after an exception.
  • Write with write() (one string, returns a count) and writelines() (many strings); add \n and str() yourself.
  • Read with read(), readline() ('' at the end), readlines() or, best, for line in f:.
  • File errors are kinds of OSError (FileNotFoundError, PermissionError…); catch the ones you expect.
  • کاتێک کۆتایی دێت لەناو دەچن؛ لەسەر دەپارێزێت.
  • کۆدی لە دێڕدا هەڵدەگرن کە بە \n کۆتایی دێن؛ تر هەڵدەگرن. بە encoding="utf-8" و بە b بکەرەوە.
  • open(name, mode) دەگەڕێنێتەوە. دۆخەکان: r خوێندنەوە ( نەبوو = )، w نووسین (دەسڕێتەوە)، a زیادکردن (لە کۆتاییدا)، x تەنها نوێ، + خوێندنەوە و نووسین.
  • with open(...) as f: بۆت دادەخات، تەنانەت دوای .
  • بە write() (یەک ، ژمارەیەک دەگەڕێنێتەوە) و writelines() (چەند ) بنووسە؛ خۆت \n و str() زیاد بکە.
  • بە read()، readline() (لە کۆتاییدا '')، readlines() یان، باشتر، for line in f: بخوێنەوە.
  • جۆرێکن لە OSError (FileNotFoundError، PermissionError…)؛ ئەوانەی چاوەڕێیان دەکەیت بگرە.

Next, Moving in a File and Saving Python Objects shows how to move the file position with tell() and seek() and how to save whole lists and dictionaries with pickle or JSON. Files are the first step in keeping data. When many programs and many users must share large amounts of data safely, files are not enough, and a database takes over (The file-based approach shows why). Other technologies handle files too: a web server receives uploaded files in PHP file uploads, and a phone app keeps its data with local storage in Flutter.

دواتر، وانەی جووڵە لەناو فایلێکدا و هەڵگرتنی ئۆبجێکتەکانی Python فێرت دەکات چۆن شوێنی بە tell() و seek() بجووڵێنیت و چۆن و بە pickle یان JSON هەڵبگریت. یەکەم هەنگاون بۆ پاراستنی . کاتێک زۆر و زۆر دەبێت بڕێکی زۆر بە سەلامەتی هاوبەش بکەن، بەس نین و جێیان دەگرێتەوە (سیستەمی پشتبەستوو بە فایل پیشان دەدات بۆچی). تەکنەلۆجیاکانی تریش مامەڵە لەگەڵ دەکەن: بارکراو وەردەگرێت لە بارکردنی فایل لە PHPـدا و ئەپێکی مۆبایل خۆی دەپارێزێت بە خەزنکردنی ناوخۆیی لە Flutterـدا.

Review questionsپرسیارەکانی پێداچوونەوە
Which modes create a missing file?کام دۆخانە فایلێکی نەبوو دروست دەکەن؟

w, w+, a, a+ and x (with or without b). r and r+ raise FileNotFoundError.

w، w+، a، a+ و x (لەگەڵ b یان بەبێ ئەو). r و r+ FileNotFoundError دروست دەکەن.

What does readline() return at the end of a file?readline() لە کۆتایی فایلێکدا چی دەگەڕێنێتەوە؟

The empty string ''. A blank line is '\n', so '' always means the end.

بەتاڵ ''. دێڕی بەتاڵ '\n'ـە، بۆیە '' هەمیشە واتە کۆتایی.

Why open files with with?بۆچی فایلەکان بە with بکەینەوە؟

It closes the file when the block ends, even after an exception, so the last writes are not lost.

کاتێک بلۆکەکە کۆتایی دێت دادەخات، تەنانەت دوای ، بۆیە دوایین نووسینەکان ون نابن.

What does f.write("Hi\n") return?f.write("Hi\n") چی دەگەڕێنێتەوە؟

3: the number of characters written. write() adds no newline of its own.

3: ژمارەی . write() هیچ دێڕێکی نوێ لە خۆیەوە زیاد ناکات.

Videoڤیدیۆ

Watch a videoسەیری ڤیدیۆیەک بکە

A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.

Python File Handling - Visually ExplainedVisually Explained · Englishئینگلیزی · 73K viewsبینین · 2.8K likesلایک

Reading, writing and appending text files, why a file must be closed, the with statement, and files in other folders.

خوێندنەوە، نووسین و زیادکردن بۆ ، بۆچی دەبێت دابخرێت، with و لە تردا.

A 14-minute overview: reading (0:50), writing (5:05), appending (7:12), why close files (8:59), with (10:23), files elsewhere: paths (11:41).

پێداچوونەوەیەکی ⁦14⁩ خولەکی: خوێندنەوە ⁦(0:50)⁩، نووسین ⁦(5:05)⁩، زیادکردن ⁦(7:12)⁩، بۆچی دادەخرێن ⁦(8:59)⁩، with ⁦(10:23)⁩ و لە شوێنی تر: ⁦(11:41)⁩.

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

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

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

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

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

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

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