Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
write(), writelines(), & Stream IterationFile I/O bridges the volatile memory of your Python script with permanent disk storage. Once a file is opened in 'w', 'a', or 'r' mode, Python provides a suite of methods to transfer text data into and out of files.
However, writing to files differs from printing to the console screen in subtle ways: while print() automatically appends a newline character (\n) at the end of every call, file writing methods do not. You must manage newlines, line breaks, and stream iteration explicitly.
+-------------------------------------------------------------------------------+
| READING & WRITING REAL-WORLD ANALOGIES |
+-------------------------------------------------------------------------------+
1. THE COURT STENOGRAPHER'S FOUNTAIN PEN (`.write()`):
- The stenographer writes words on a continuous parchment roll.
- When you write "Item 1", the pen does NOT jump to the next line
by magic—the stenographer must explicitly pull the carriage return lever
(`\n`) to begin a new line.
- You can write strings of any length; the method reports the exact count
of characters pressed into the page.
2. THE ARCHIVAL INDEX CARD BUNDLE (`.writelines()`):
- A postal clerk holds a rubber-banded stack of 10 pre-printed cards.
- `.writelines()` pastes all 10 cards onto the manifest page in one stroke.
- Crucial Note: If each card did not already have a newline stamped on its
bottom edge, they all stick together in one continuous unbroken sentence!
3. THE LINE-BY-LINE MAGNIFYING GLASS (`for line in file:`):
- Reading a 500-page property deed one line at a time.
- You only look at 1 line in memory at any millisecond, keeping your desk
clean even if the book weighs 10 kilograms.
+-------------------------------------------------------------------------------+.write()The .write(string) method writes a string to the open file and returns the integer number of characters written:
.write() strictly accepts strings (str). Passing an integer, float, or list (e.g. f.write(450)) raises an immediate TypeError: write() argument must be str, not int. Always cast non-strings using str() or f-strings: f.write(f"{amount}\n")..writelines()The .writelines(iterable) method takes an iterable of strings (such as a list of strings) and writes them to the file in sequence:
.writelines() does NOT insert newline characters between items! If the strings in your list do not end with \n, they will be concatenated into one giant single line.Python provides three distinct techniques to read data from a text file:
+---------------------------+-----------------------------------+-------------------------------------+ | METHOD | HOW IT WORKS | MEMORY PROFILE | +---------------------------+-----------------------------------+-------------------------------------+ | `f.read()` | Reads the ENTIRE file as one str | Loads entire file into RAM. Risky | | | into memory. | for large files (> 1 GB). | +---------------------------+-----------------------------------+-------------------------------------+ | `f.readlines()` | Reads entire file into a list of | Loads entire list into RAM. | | | string lines: `['L1\n', 'L2\n']`. | Retains trailing newlines. | +---------------------------+-----------------------------------+-------------------------------------+ | `for line in f:` | Streams one line at a time | EXTREMELY EFFICIENT! Uses O(1) | | (Stream Iteration) | lazily on demand. | RAM even for a 50 GB log file! | +---------------------------+-----------------------------------+-------------------------------------+
Iterating directly over the file object is the most memory-efficient and Pythonic way to read text files:
Output:
f.read(size)You can pass an optional integer argument to read(size) to read only a specified number of characters:
Output:
| Best Practice (DO) | Dangerous Anti-Pattern (DON'T) |
|---|---|
DO use for line in file: for line-by-line parsing to maintain $O(1)$ memory usage. | DON'T call file.read() on massive 10 GB log files, which exhausts system RAM. |
DO explicitly append \n when calling .write() or preparing lists for .writelines(). | DON'T pass non-strings to .write(); cast them first with str() or f-strings. |
DO use .strip() on lines read from a file to remove trailing \n characters. | DON'T assume .writelines() automatically adds line breaks between list items. |
.write(string) writes text to a file and returns character count; does not append automatic newlines..write() causes a TypeError..writelines(list_of_strings) writes a batch of strings to disk without inserting automatic newlines.for line in file: provides lazy, memory-efficient stream iteration ($O(1)$ memory).line.strip() or line.rstrip('\n') when processing lines read from files to clean up trailing line breaks.Always use the with open() context manager so files are automatically closed even if an exception occurs:
'w' ModeOpening an existing file in 'w' (write) mode immediately truncates (erases) all existing content! To preserve existing data and add to the end, use 'a' (append) mode.
file.write(500) where file is opened in text write mode?A. Python converts 500 to string "500" automatically B. Python raises a TypeError: write() argument must be str, not int C. Python writes 500 blank spaces to the file D. Python writes 500 binary bytes
.write() from print() regarding newline characters?A. print() adds no newlines; .write() adds two newlines B. print() automatically appends a newline \n by default, whereas .write() only writes the exact characters supplied without any automatic newline C. .write() cannot write newlines D. There is no difference; they are aliases
lines = ["Apple", "Banana", "Cherry"], what will appear in a file written with f.writelines(lines)?A. Three separate lines: Apple, Banana, Cherry B. A single continuous line: AppleBananaCherry C. A list formatted as ['Apple', 'Banana', 'Cherry'] D. An error because commas are missing
A. data = f.read() B. lines = f.readlines() C. for line in f: D. list(f)
.strip() frequently called on lines during file reading (e.g. for line in f: clean_line = line.strip())?A. To convert the text to lowercase B. To strip out and remove the invisible trailing newline character \n that .readline() and stream iteration retain C. To encrypt the string in memory D. To convert the string to a list of tokens
Build an automated grade export and parsing engine for a CBSE high school examination board.
export_student_marks_csv(filename, student_records):(roll_no, name, marks, grade).filename in write mode 'w'."Roll_No,Student_Name,Marks,Grade\n".\n.import_and_analyze_marks_csv(filename):filename in read mode 'r'.for line in f:) to parse the file line by line., and calculates: Total Students, Class Average Marks, and Top Scorer Name.In the next lesson, we will continue your Python learning journey with Working with open() (15: File Handling).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Opening & Closing Files | Working with open() |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.