13. Files
To write a file and read its lines.
Explanation
Section titled “Explanation”- 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
Section titled “Example”استورد ملفاتجرّب ملفات.اكتب_ملف("قائمة.txt", "خبز\nحليب\n")لكل غرض في جرّب ملفات.اقرأ_سطور("قائمة.txt"): اطبع("- ", غرض)Common mistakes
Section titled “Common mistakes”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.
استورد ملفاتملفات.اكتب_ملف("ناتج.txt", "سطر\n")Exit code: 2
In the error catalog: E0397
استورد ملفاتملفات.اكتب_ملف("ناتج.txt", "سطر\n") والا خ: اطبع("تعذّرت الكتابة: ", خ)جرّب ملفات.الحق_بملف("ناتج.txt", "سطر ثانٍ\n")اطبع(جرّب ملفات.اقرأ_ملف("ناتج.txt"))Exercise
Section titled “Exercise”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
استورد ملفاتجرّب ملفات.اكتب_ملف("مهام.txt", "اشترِ خبزاً\nراجع الدرس الثاني عشر\nاتصل بجدتي\n")سطور = جرّب ملفات.اقرأ_سطور("مهام.txt")اطبع("عدد المهام: ", طول(سطور))اطول = ""لكل س في سطور: اذا طول(س) > طول(اطول): اطول = ساطبع("أطولها: ", اطول)See also
Section titled “See also”The ملفات module · Error handling