Working with files
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
Variables vanish when a program ends; files stay on disk. Step through a six-line program, files.py, that writes a two-item shopping list to shop.txt and reads it back. Watch open() hand you a file object, see the writes wait in a buffer until with closes the file, read the file one line at a time, and meet the error you get when a file is missing.
5 أسئلة سريعة
اختر إجابة لتعرف السبب. تُحفَظ نتيجتك مع تقدّمك.
01notes.txt already holds 3 lines. What does open("notes.txt", "w") do to it?
"w" opens for writing and truncates: an existing file is emptied first (a missing one is created). Use "a" to add to the end instead.
02A program runs f.write("hi") and then f.write("there") on the same file. What does the file contain?
write() adds exactly the characters you give it, with no space or newline of its own. Write "hi\n" if you want the line to end.
03Right after f.write("milk\n") inside a with block, the file on disk is still 0 bytes. Why?
File objects are buffered for speed. Closing (which with does when its block ends) or f.flush() sends the buffered text to the disk.
04shop.txt holds milk and eggs on two lines. What does for line in f: print(line) show?
Each line keeps its \n, and print() adds its own newline, so a blank line follows each item. line.strip() removes the extra one.
05What happens when a program runs open("todo.txt") and there is no todo.txt?
The default mode "r" needs the file to exist, so open() raises FileNotFoundError: [Errno 2] No such file or directory: 'todo.txt'.
المسرد
- File
- Named data saved on disk. Unlike a variable, it is still there after the program ends.
- open()
- A built-in function that opens a file by name and returns a file object to read or write it.
- Mode
- The second argument to open(): "r" read (the default), "w" write (create or empty first), "a" append, "x" create new only; add "b" for bytes.
- File object
- What open() returns: it remembers which file is open, in which mode, and where you are in it. Here it is named f.
- Buffer
- Memory where a file object collects written text before sending it to the disk in one go, when the buffer fills, on flush() or on close.
- with statement
- Runs an indented block with the file open and closes the file when the block ends, even if an error happens.
- Newline (\n)
- The character that ends a line of text. write() does not add it for you; reading a file line by line keeps it.
- FileNotFoundError
- The error open() raises when you ask to read a file that does not exist.
الملاحظات والمصادر
- File objects are buffered: small writes wait in memory until the buffer fills, you call f.flush(), or the file is closed. The Python tutorial warns that without with or f.close(), what you wrote might not all reach the disk, even if the program ends normally.
- The 10 characters are 10 bytes here because milk and eggs are plain letters. On Windows, text mode writes each \n as \r\n, so the same file is 12 bytes there.
- Text mode turns characters into bytes with an encoding. Without encoding=..., open() uses your system's default; passing encoding="utf-8" makes a program behave the same everywhere.
- Modes: "r" read (the default), "w" write (create or empty first), "a" append to the end, "x" create only if the file does not exist yet. Add "b" for raw bytes, as in "rb".
- A bare name such as shop.txt is looked up in the current working directory: the folder you ran python from.
- The figure shortens the error. The real message shows the full path to files.py, then line 4 itself with ^ marks under the call, and prints the last line in one piece; a narrow terminal wraps it.
- Python tutorial: Reading and writing files
- Python library: Built-in functions, open()
- Python library: io (text files, buffering, flush)
- Python reference: The with statement
- Python library: str.strip()
- Python library: Built-in exceptions, FileNotFoundError
- Python glossary: file object
- Python library: os.linesep
اختبار يتاح بعد الخطوة الأخيرة.