Skip to content
العربية

13. Files

To write a file and read its lines.

  • After استورد ملفات (import files), ملفات.اكتب_ملف(مسار, نص) (write file) writes the text to the file: it creates the file if it does not exist, replaces its whole content if it does, and does not add a newline at the end.
  • ملفات.اقرأ_سطور(مسار) (read lines) returns a list of the file’s lines, so it reads the whole file into memory.
  • For a large file, read it line by line (since 0.14.0): ق = جرّب ملفات.افتح_للقراءة(مسار) (open for reading) then خاتمه ملفات.اغلق(ق) (close), and ملفات.اقرأ_سطر(ق) (read line) returns the next line or لاشيء (nothing) at the end of the file. For writing there are ملفات.افتح_للكتابة and ملفات.اكتب_سطر, and for binary files اقرأ_ملف_بايتات and اكتب_ملف_بايتات. Details in the files module.
  • The functions of ملفات can fail (the file does not exist, or there is no permission), so write جرّب (try) before them.
  • The ملفات module is experimental.
Example
استورد ملفات
جرّب ملفات.اكتب_ملف("قائمة.txt", "خبز\nحليب\n")
لكل غرض في جرّب ملفات.اقرأ_سطور("قائمة.txt"):
اطبع("- ", غرض)
Output recorded in the reference handbookmeem برنامج.م · 0.17.1
- خبز- حليب

Forgetting جرّب or والا with a function that can fail: this is a compile error, and its message tells you what to write. And note: جرّب at the top level of the file ends the program with exit code 3 if the function fails.

Causes the error
استورد ملفات
ملفات.اكتب_ملف("ناتج.txt", "سطر\n")
Output recorded in the reference handbookmeem برنامج.م · 0.17.1
​[خطأ دلالي E0397] مثال.م:2:7 - نتيجة 'ملفات.اكتب_ملف(...)' من النوع '!فراغ' مهملة: قد يكون خطأً لم يُعالَج   2 | ملفات.اكتب_ملف("ناتج.txt", "سطر\n")     |       ^~~~~~~~~~~~~~  تلميح: عالج الخطأ في موضعه:  جرّب ملفات.اكتب_ملف(...)  (يمرّر الخطأ إلى مستدعي الدالة)   أو   ملفات.اكتب_ملف(...) والا خ:  ثم كتلة   أو   ملفات.اكتب_ملف(...) والا خ:  ثم كتلة تعالج «خ»

Exit code: 2

In the error catalog: E0397

Fixes it
استورد ملفات
ملفات.اكتب_ملف("ناتج.txt", "سطر\n") والا خ:
اطبع("تعذّرت الكتابة: ", خ)
جرّب ملفات.الحق_بملف("ناتج.txt", "سطر ثانٍ\n")
اطبع(جرّب ملفات.اقرأ_ملف("ناتج.txt"))
Output recorded in the reference handbookmeem برنامج.م · 0.17.1
سطرسطر ثانٍ​

Write three tasks to the file «مهام.txt», one line per task, then read them back and print how many there are and the longest one.

Show the solution
Solution
استورد ملفات
جرّب ملفات.اكتب_ملف("مهام.txt", "اشترِ خبزاً\nراجع الدرس الثاني عشر\nاتصل بجدتي\n")
سطور = جرّب ملفات.اقرأ_سطور("مهام.txt")
اطبع("عدد المهام: ", طول(سطور))
اطول = ""
لكل س في سطور:
اذا طول(س) > طول(اطول):
اطول = س
اطبع("أطولها: ", اطول)
Output recorded from the compilermeem 12_حل.م · meem 0.17.3+434e13f
عدد المهام: 3أطولها: راجع الدرس الثاني عشر

The ملفات module · Error handling