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، نووسین و خوێندنەوەی دێڕەکان، گۆڕینی دێڕەکان بۆ وشە و ژمارە و .
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 withwrite()andwritelines(). - Read files with
read(),readline(),readlines()and aforloop, and turn lines into words and numbers. - Catch the errors files cause, such as
FileNotFoundErrorandPermissionError, 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)ـدا دەژین. ئەم چایە دوو جار کار پێ بکە: جاری دووەم دیسان لە سفرەوە دەست پێ دەکاتەوە.
total = 0 # every run starts again from zero
teas = int(input("Teas sold just now: "))
total = total + teas
print("Teas sold today:", total)Teas sold just now: 3 Teas sold today: 3 Teas sold just now: 5 Teas sold today: 5
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
totalis 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 یان . دوای کۆتایی هاتنی و دوای دەمێنێتەوە (کوژاندنەوە: چی دەمێنێت و چی دەڕوات هۆکارەکەی ڕوون دەکاتەوە). دوکانێک کاڵاکانی، قوتابخانەیەک نمرەکان و فەرمانگەیەک ناوی کارمەندەکانی بەم شێوەیە هەڵدەگرێت.
A named collection of stored on a computer, such as a document, a photo, a song or a . Its shows its type.
کۆمەڵێک ناونراوە کە لەسەر کۆمپیوتەر هەڵگیراوە، وەک بەڵگەنامەیەک، وێنەیەک، گۆرانییەک یان . جۆرەکەی پیشان دەدات.
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ـدا دەیبینیت.
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 دەخوێنێتەوە، چا نوێیەکان زیاد دەکات و کۆ نوێیەکە دەنووسێتەوە. ئێستا جاری دووەم لە شوێنی جاری یەکەمەوە بەردەوام دەبێت. ئێستا خەمی وردەکارییەکان مەخۆ: لە کۆتایی ئەم وانەیەدا دەتوانیت هەموو دێڕێک ڕوون بکەیتەوە.
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)Teas sold just now: 3 Teas sold today: 3 Teas sold just now: 5 Teas sold today: 8
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 file | codes of characters; each line ends with a newline \nکۆدی ؛ هەر دێڕێک بە دێڕی نوێ \n کۆتایی دێت | .txt .py .csv .html | any text editor (Notepad, VS Code)هەر (Notepad، VS Code) |
| Binary file | anything else: pixels, sound, machine code, packed partsهەر شتێکی تر: ، دەنگ، ، بەشی پەستێنراو | .png .jpg .mp3 .mp4 .zip .exe .docx | the 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. ئەم دوو دێڕی کورت دەنووسێت و پاشان وەک خاو دەخوێنێتەوە:
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))17 bytes [72, 105, 32, 65, 114, 97, 109, 10, 216, 179, 218, 181, 216, 167, 217, 136, 10]
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ـێکدا دێڕێکی نوێ دەست پێ دەکات.
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 ئەمە پیشان دەدەن:
# 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())Traceback (most recent call last):
File "png_as_text.py", line 6, in <module>
print(f.read())
^^^^^^^^
File "<frozen codecs>", line 322, in decode
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byteBinary 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.
ناسکیشن: تەنها یەک لە وێنەیەک یان بگۆڕە، لەوانەیە هەر نەکرێتەوە. کە یەک پیتی هەڵەی تێدایە هێشتا مرۆڤ دەتوانێت بیخوێنێتەوە و ڕاستی بکاتەوە. دەتوانێت هەردوو جۆر بخوێنێتەوە و بنووسێت؛ ئەو دۆخەی پێ دەکەیتەوە بڕیار دەدات کامیان.
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) کردمان:
| File | Sizeقەبارە | What is insideچی تێدایە |
|---|---|---|
name.txt | 6 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 پێویستە. (پاشگرەکانی فایل و جۆرەکانی فایل جۆری زیاتر دەناسێنێت.)
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() دەیکاتەوە. ناوی ، دۆخێک کە دەڵێت دەتەوێت چی بکەیت و بۆ پێویستە:
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)name: notes.txt mode: w closed: False closed: True
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(),closedisTrue.دوای
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 زانیاریت دەربارەی پێ دەدەن.
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() بەستنەوەکە کۆتایی پێ دەهێنێت.
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" بەکار دەهێنێت: خوێندنەوەی . خوێندنەوەی کە بوونی نییە :
f = open("shopping.txt", encoding="utf-8") # read mode: the default
print(f.read())Traceback (most recent call last):
File "open_missing.py", line 1, in <module>
f = open("shopping.txt", encoding="utf-8") # read mode: the default
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'shopping.txt'Run with Python 3.12. Python 3.13 marks the failing code a little differently in tracebacks; the error message is the same.
بە 3.12 کاری پێکراوە. 3.13 لە کۆدە هەڵەکە کەمێک بە شێوەیەکی تر نیشان دەدات؛ پەیامی هەمان شتە.
Later in this lesson you will catch this error instead of crashing (Errors you will meet).
دواتر لەم وانەیەدا ئەم دەگریت لەبری ئەوەی بکەوێت (چەند هەڵەیەک کە تووشیان دەبیت).
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: 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")Traceback (most recent call last):
File "path_folder.py", line 2, in <module>
with open("data/marks.txt", "w", encoding="utf-8") as f:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'data/marks.txt'
(after making the folder data)
savedOn 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".
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 لە دەقەوە دەیگۆڕێت بۆ دووانی. پێش ئەوەی بکەیتەوە، سێ پرسیار بکە: ئایا نەبوو دروست دەکرێت؟ ئایا ناوەڕۆکی کۆن دەسڕدرێتەوە؟ خوێندنەوە یان نووسین لە کوێوە دەست پێ دەکات؟
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، بنەڕەتییەکە). دۆخەکە بڕیار دەدات ئایا نەبوو دروست دەکرێت، ئایا ناوەڕۆکی کۆن دەسڕدرێتەوە و خوێندنەوە یان نووسین لە کوێوە دەست پێ دەکات.
| Modeدۆخ | Jobکار | File missing نییە | Old contentناوەڕۆکی کۆن | Starts atلە کوێوە دەست پێ دەکات |
|---|---|---|---|---|
r | read only (the default)تەنها خوێندنەوە (بنەڕەت) | error: FileNotFoundError: FileNotFoundError | keptدەمێنێت | startسەرەتا |
r+ | read and writeخوێندنەوە و نووسین | error: FileNotFoundError: FileNotFoundError | kept (overwritten only where you write)دەمێنێت (تەنها لەو شوێنەی دەنووسیت جێی دەگیرێتەوە) | startسەرەتا |
w | write onlyتەنها نووسین | createdدروست دەکرێت | erasedدەسڕدرێتەوە | startسەرەتا |
w+ | write and readنووسین و خوێندنەوە | createdدروست دەکرێت | erasedدەسڕدرێتەوە | startسەرەتا |
a | append: write at the endزیادکردن: نووسین لە کۆتاییدا | createdدروست دەکرێت | keptدەمێنێت | endکۆتایی |
a+ | append and readزیادکردن و خوێندنەوە | createdدروست دەکرێت | keptدەمێنێت | end (writing always goes to the end)کۆتایی (نووسین هەمیشە دەچێتە کۆتایی) |
x | create a new file and writeدروستکردنی نوێ و نووسین | createdدروست دەکرێت | error if the file exists: FileExistsErrorئەگەر هەبێت : FileExistsError | startسەرەتا |
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+: زیادکردن بۆ کۆتایی و خوێندنەوەی؛ ئەگەر نەبێت دروست دەکرێت؛ لە کۆتاییەوە دەست پێ دەکات.
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ـی تێدایە بە هەر دۆخێک دەکاتەوە و ڕایدەگەیەنێت چی ڕووی دا:
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)r creates: no: FileNotFoundError erases: no starts at: start r+ creates: no: FileNotFoundError erases: no starts at: start w creates: yes erases: yes starts at: start w+ creates: yes erases: yes starts at: start a creates: yes erases: no starts at: end a+ creates: yes erases: no starts at: end x creates: yes FileExistsError (file is there) rb creates: no: FileNotFoundError erases: no starts at: start rb+ creates: no: FileNotFoundError erases: no starts at: start wb creates: yes erases: yes starts at: start wb+ creates: yes erases: yes starts at: start ab creates: yes erases: no starts at: end ab+ creates: yes erases: no starts at: end
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
Binary modes take no encoding, so
encisNonefor them.دۆخە دووانییەکان وەرناگرن، بۆیە
encبۆ ئەوانNoneـە.- Lineدێڕی 6-14
A missing file: does
open()create it or raiseFileNotFoundError?نەبوو: ئایا
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
OLDstill 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 دروست دەکات:
# 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}")r : read ok r : write fails: UnsupportedOperation: not writable w : read fails: UnsupportedOperation: not readable w : write ok a : read fails: UnsupportedOperation: not readable a : write ok r+: read ok r+: write ok
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()ـێک یەکسەر نانێرێت بۆ دیسک: دەقەکە لە لە کۆ دەکاتەوە و پارچەی گەورەتر دەنووسێت، کە زۆر خێراترە. دەتوانیت ببینیت چۆن ڕوو دەدات:
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")Size before close(): 0 bytes Size after close(): 20 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() دەنووسێت بەبێ داخستن، بۆ کە بۆ کاتێکی درێژ کراوە دەهێڵێتەوە.
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 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)Inside with: closed? False After with: closed? True After an error: closed? True
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
with open(...) as f:opens the file and names the file objectf.with open(...) as f:دەکاتەوە و ناوی دەنێتf.- Lineدێڕی 4
The block has ended, so the file is closed.
بلۆکەکە کۆتایی هات، بۆیە داخرا.
- Lineدێڕی 9
A
ValueErrorjumps out of the block, butwithstill 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)، بە دێڕی کەمتر:
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)closed? True
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() بکە بە .
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())13 3 15 Tea glasses: 48 پەرداخی چا: 48
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\nthat 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() لەبیر بکەیت، ڕێگەت پێ نادات:
with open("stock.txt", "w", encoding="utf-8") as f:
f.write(48)Traceback (most recent call last):
File "write_int.py", line 2, in <module>
f.write(48)
TypeError: write() argument must be str, not intWriting: 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 دەگەڕێنێتەوە، نەک ژمارە.
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())Erbil Sulaymaniyah Duhok
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() دەتوانێت ژمارە وەربگرێت؟ نەخێر، دەبێت هەموو دانەیەک بێت:
with open("prices.txt", "w", encoding="utf-8") as f:
f.writelines((500, 750, 1000)) # a tuple of numbersTraceback (most recent call last):
File "writelines_numbers.py", line 2, in <module>
f.writelines((500, 750, 1000)) # a tuple of numbers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: write() argument must be str, not intAnd 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 دروست دەکات. بۆ هەڵگرتنی ژمارەکان، خۆت هەر یەکێکیان بکە بە دێڕێکی دەق:
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="")500 750 1000
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 هەر جارێک لە بەتاڵەوە دەست پێ دەکاتەوە. ئەمە دوو بچووکن، هەر یەکەیان دوو جار کاری پێکراوە. یەکەمیان زیاد دەکات:
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="")Dilan Dilan Dilan
The second is the same program with "w" in line 1. The second run erased the first visitor:
دووەمیان هەمان بە "w" لە دێڕی 1ـدا. جاری دووەم یەکەم سەردانکەری سڕییەوە:
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="")Dilan Dilan
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:
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 پیشان دەدات.)
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'Aram' ' 17' '\nShilan 19\nKarwan 15\n' ''
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-3
Each call continues where the last one stopped.
هەر بانگکردنێک لەو شوێنەوە بەردەوام دەبێت کە پێشووەکە وەستا.
- Lineدێڕی 5
Nothing is left:
''.هیچی تر نییە:
''.
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' دەگەڕێتەوە، بۆیە '' تەنها دەتوانێت مانای کۆتایی بێت.
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'Aram 17\n' 'Shilan 19\n' 'Karwan 15\n' ''
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()، لە دووبارەی بکەرەوە کە لە ''ـدا دەوەستێت:
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()Aram 17 Shilan 19 Karwan 15
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.
پێش ئەوەی تاقیکردنەوەکە دووبارە بێتەوە دێڕی داهاتوو بخوێنەوە. ئەم دێڕە لەبیر بکەیت، هەرگیز کۆتایی نایەت.
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 کۆتایی دێت:
with open("marks.txt", encoding="utf-8") as f:
lines = f.readlines()
print(lines)
print(len(lines), "lines")['Aram 17\n', 'Shilan 19\n', 'Karwan 15\n'] 3 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:
باشترین ڕێگا بۆ زۆربەی بەسەر خودی . لە هەر خولانەوەیەکدا یەک دێڕ دەخوێنێتەوە، تەنانەت بۆ زۆر گەورەش کەم بەکار دەهێنێت و پێویستی بە تاقیکردنەوەی '' نییە:
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)Aram 17 Shilan 19 Karwan 15
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نزیکەی هەمیشە: سادەیە و بۆ گەورە باشە |
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ـەکەی دەدات، لە یەک دانەییدا:
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['Aram', '17'] ['Shilan', '19'] ['Karwan', '15'] ['Aram 17'] ['Shilan 19'] ['Karwan 15']
Everything read from a text file is text. To calculate with it, convert it: int("17") is the number 17.
هەموو ئەوەی لە دەخوێنرێتەوە دەقە. بۆ ژماردن پێی، بیگۆڕە: int("17") ژمارە 17ـە.
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)Total: 51
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ـە:
name,maths,physics Aram,17,15 Shilan,19,18 Karwan,15,16
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}")['name', 'maths', 'physics'] [['Aram', 17, 15], ['Shilan', 19, 18], ['Karwan', 15, 16]] Aram average 16.0 Shilan average 18.5 Karwan average 15.5
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.
لە کۆماکاندا لەتی بکە و نمرەکان بکە بە ژمارە.
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 دەنووسێت. لە هەڵیان دەگرێت، هەر یەکەیان لە دێڕێکدا، پاشان دەخوێنێتەوە و تەنها ئەو ڕستانە پیشان دەدات کە بە پیتی گەورە دەست پێ دەکەن.
- Open for writingکردنەوە بۆ نووسین
Open
sentences.txtwith"w"(a new, empty file).sentences.txtبە"w"بکەرەوە ( نوێی بەتاڵ). - Save until ENDهەڵگرتن تا END
Repeat: read a sentence; stop at
END; otherwise write it with\n.دووبارە بکەرەوە: ڕستەیەک بخوێنەوە؛ لە
ENDـدا بوەستە؛ ئەگینا لەگەڵ\nبینووسە. - Read backخوێندنەوە
Close it, open it again for reading and walk through the lines.
دایبخە، دیسان بۆ خوێندنەوە بیکەرەوە و بە دێڕەکاندا بڕۆ.
- Filterپاڵاوتن
Print a line only if its first character is a capital letter.
دێڕێک تەنها کاتێک چاپ بکە کە یەکەم پیتێکی گەورە بێت.
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)Type a sentence (END to stop): Erbil is a big city Type a sentence (END to stop): the tea is ready Type a sentence (END to stop): Python is fun Type a sentence (END to stop): کوردستان جوانە Type a sentence (END to stop): Type a sentence (END to stop): END Sentences that start with a capital letter: Erbil is a big city Python is fun
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-6
The
withblock keeps the file open while the loop writes; it closes when the loop ends.بلۆکی
withکراوە دەهێڵێتەوە تا دەنووسێت؛ کاتێک کۆتایی هات دادەخرێت.- Lineدێڕی 6
input()gives no newline, so add\nyourself.input()دێڕی نوێ نادات، بۆیە خۆت\nزیاد بکە.- Lineدێڕی 12
line != ""protectsline[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()ـیش هەروەها (پیتی گەورە و بچووک).
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:
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)FileNotFoundError - [Errno 2] No such file or directory: 'missing.txt' IsADirectoryError - [Errno 21] Is a directory: 'data' FileExistsError - [Errno 17] File exists: 'marks.txt' PermissionError - [Errno 13] Permission denied: 'secret.txt' True
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 10
except OSErrorcatches all four, because they are all kinds ofOSError.except OSErrorهەر چواریان دەگرێت، چونکە هەموویان جۆرێکن لەOSError.- Lineدێڕی 13
IOErroris just another name forOSError.IOErrorتەنها ناوێکی ترە بۆOSError.
| Exception | Whenکەی |
|---|---|
FileNotFoundError | reading a file that does not exist, or a folder in the path is missingخوێندنەوەی کە بوونی نییە، یان لە نییە |
FileExistsError | mode x, but the file is already thereدۆخی x، بەڵام پێشتر هەیە |
IsADirectoryError | the name is a folder (Windows says PermissionError here)ناوەکە (Windows لێرەدا دەڵێت PermissionError) |
PermissionError | no right to read or write the file, for example a protected system fileمافی خوێندنەوە یان نووسینی نییە، بۆ نموونە پارێزراوی سیستەم |
UnicodeDecodeError | the bytes do not fit the encoding: a binary file opened as text, or a wrong encoding لەگەڵ ناگونجێن: وەک دەق کراوەتەوە، یان هەڵە |
ValueError | reading or writing a closed file: I/O operation on closed fileخوێندنەوە یان نووسینی داخراو: I/O operation on closed file |
io.UnsupportedOperation | reading in w or a, writing in r, a relative seek in text modeخوێندنەوە لە w یان a، نووسین لە r، seekـی ڕێژەیی لە دۆخی دەقدا |
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 بگرە (هەڵاوێردەکانی چاوەڕوانکراو بگرە) و دەتوانێت دیسان بپرسێت لەبری ئەوەی بکەوێت:
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)File to show: shopping.txt There is no file called shopping.txt File to show: data data is a folder, not a file File to show: marks.txt Aram 17 Shilan 19 Karwan 15
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 6
breakonly runs when the file was opened and shown.breakتەنها کاتێک جێبەجێ دەبێت کە کرابێتەوە و پیشان درابێت.- Lineدێڕی 7-12
One
exceptfor each problem the user can cause. (On Windows a folder name givesPermissionError, 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. دروست دەکات.
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 int | f.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خوێندنەوەی دوای بلۆکی with | ValueError: I/O operation on closed file. | indent the reading lines inside the blockدێڕەکانی خوێندنەوە بخەرە ناو بلۆکەکە |
Exercises: explain and chooseڕاهێنانەکان: ڕوونکردنەوە و هەڵبژاردن
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 دەگەڕێنێتەوە. هیچیان دێڕی نوێ زیاد ناکەن. |
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وەڵامەکە پیشان بدە
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 encodingFor (a), "w+" would also read and write, but it erases the diary first.
بۆ (أ)، "w+"یش دەخوێنێتەوە و دەنووسێت، بەڵام سەرەتا دەفتەری ڕۆژانەکە دەسڕێتەوە.
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ڕاهێنانەکان: بەرنامەکان
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وەڵامەکە پیشان بدە
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)with open("hello.txt", encoding="utf-8") as f:
print(f.read(), end="")Hello! Welcome to our class Here we learn and play Tea is at ten o'clock
With "w" the file would be emptied first: Hello! would be gone and only the three new lines would be left.
بە "w" سەرەتا بەتاڵ دەکرایەوە: Hello! نەدەما و تەنها سێ دێڕە نوێکە دەمانەوە.
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وەڵامەکە پیشان بدە
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="")Aram 17 Shilan 19
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-2
Two files in one
with: one to read, one to write.دوو لە یەک
withـدا: یەکێک بۆ خوێندنەوە و یەکێک بۆ نووسین.
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وەڵامەکە پیشان بدە
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")Order 1 on 2026-10-24: 13000 IQD Order 2 on 2026-10-24: 5500 IQD Order 1 on 2026-10-25: 2000 IQD Summary for 2026-10-24 Kebab 2 Tea 3 Dolma 1 Total: 18500 IQD
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 withencoding="utf-8", binary files withb. open(name, mode)returns a file object. Modes:rread (missing file = error),wwrite (erases),aappend (at the end),xnew 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) andwritelines()(many strings); add\nandstr()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ـدا.
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.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
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زاراوە سەرەکییەکان
Moving in a File and Saving Python Objectsجووڵە لەناو فایلێکدا و هەڵگرتنی ئۆبجێکتەکانی Python
Related lecturesوانە پەیوەندیدارەکان
- Moving in a File and Saving Python Objectsجووڵە لەناو فایلێکدا و هەڵگرتنی ئۆبجێکتەکانی Python
- Tuples, Sets and Dictionariesتاپڵەکان، کۆمەڵەکان و فەرهەنگەکان
- Two-Dimensional Listsلیستە دووڕەهەندەکان
- Storage Versus Memoryخەزنکردن بەرامبەر بیرگە
- Application Software and File Typesنەرمەواڵەی بەکارهێنان و جۆرەکانی فایل
- Web APIs and JSONAPIـی وێب و JSON
- From Files to Databasesلە فایلەوە بۆ بنکەدراوە
- Stacks: Last In, First Outستاکەکان: دوایین هاتوو، یەکەم دەرچوو
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- Python Tutorial 7.2: Reading and Writing Files (modes, with, file methods, seek/tell in text mode, json, pickle note)
- Python Library: built-in function open() (modes table, encoding, newline, IOError alias)
- Python Library: built-in exceptions — OS exceptions (FileNotFoundError, PermissionError, IsADirectoryError, EOFError)
- Python Library: csv (reader, writer, newline='')
- PEP 686: Make UTF-8 mode default (Python 3.15)
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.