Concepts / Working with Strings in Python

Working with Strings in Python

A Python program can calculate results, process input, or analyze data while it is running.

  • Programming
Interactive lab

Try it: Reading and Writing Text Files

How open() returns a file object with a position pointer, how read(), read(n), readline(), readlines() and for line in fh advance it (and return '' at the end), how 'w' and 'a' modes change the file, and why a closed file (after close() or a with block) can no longer be read.

How it works

  1. open(name, 'r') starts the pointer at 0; 'w' empties the file first; 'a' starts at the end.
  2. read() returns everything from the pointer to the end; read(n) at most n characters; readline() up to and including the next \n; each moves the pointer past what it returned.
  3. At the end of the file every read returns '' (an empty string), which is how loops know to stop; for line in fh reads line by line the same way.
  4. write() text waits in a buffer and reaches the file when it is closed (or the program ends); reading a 'w'/'a' file or writing an 'r' file raises io.UnsupportedOperation.
  5. close(), or leaving a with block, closes the file; any further read raises ValueError: I/O operation on closed file.

Default run (10 steps): Ready: notes.txt holds 4 lines (51 characters). Nothing is open yet. … Finished. notes.txt now holds "From: stephen\nSubject: meeting\nFrom: louis\nThanks!\n".

Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. One virtual text file with \n line endings (as on Linux/macOS), positions counted in characters (ASCII only), and a write buffer that is only flushed by close() or the end of the program.

Educational simulation

Loading the simulation…

From Temporary Data to Saved Data

A Python program can calculate results, process input, or analyze data while it is running. Files allow that information to remain available after the program ends. File operations connect temporary in-memory work with information stored permanently on a computer.

File work follows a three-part pattern: open the file, perform an operation such as reading or writing, and close the file. The opening step selects the file and its mode. The working step uses the permissions provided by that mode. The closing step tells Python to finalize changes and release the file.

Open filefilename and modeRead or writefile operationClose filefinalize and releasecreates accessfinish operation
How does information move between a Python program and a file?

Choosing an Opening Mode

Definition

The open() function is the gateway to file operations. It takes a filename as a string and a mode that determines what the program is allowed to do with the file and what happens to existing content.

ModePurposeEffect on existing content
rReadExisting content is preserved
wWriteExisting content is erased
aAppendExisting content is preserved

The three file modes described in the source material

python
rreadwwrite; erases existingcontentaappend; preserves existingcontent
How do read, write, and append modes differ?

Following the File Pointer

When a file is read line by line, readline() returns one complete line, including its newline character. After that call, the next read begins after the line that was returned. The file pointer therefore marks the current position in the sequence of file content.

Code walkthrough
f = open("poem.txt", "r")
line_one = f.readline()
line_two = f.readline()
line_three = f.readline()
f.close()
  1. 1
    After opening, reading can begin from the file's current starting position.
  2. 2
    The first readline() call returns the first line, including its newline character when that character is part of the line.
  3. 3
    The second readline() call begins after the first returned line.
  4. 4
    The third readline() call continues from the position after the second returned line.
  5. 5
    Closing completes the file operation and releases the file.
  • Open the file for reading.
  • Read the first complete line.
  • Read the next complete line.
  • Read the next complete line.
  • Close the file.
Line 1first returned lineLine 2next returned lineLine 3next returned lineEOFempty stringreadline() advancesreadline() advancesno more content
Where is the file pointer before and after each readline() call, and what changes at the end?

Recognizing the End of a File

A call to readline() normally returns a complete line. When there is no more content to read, it returns an empty string. That empty string is the signal a program can use to stop reading instead of continuing to request more lines.

python
readline()request a lineComplete linecontinue readingEmpty stringend-of-fileStop readingclose fileline returnedrequest next lineno content remainsend condition
What does a read operation return at end-of-file, and how does control flow respond?

What do you think happens?

What does readline() return after every available line has already been read?

  • The last line again

  • An empty string

  • The filename

  • A mode value

Reveal answer
Answer:

An empty string

The source defines an empty string as the result returned by readline() at end-of-file. A program can use that result as its stopping condition.

Writing and Closing Safely

Writing sends data from the Python program into a file opened for writing. The file should then be closed with f.close(). Closing tells Python to finalize changes and releases the file so other programs can use it.

python

A context manager using a with statement is an alternative way to have a file closed automatically. The essential idea remains the same: open the file, perform the work, and ensure that the file is closed afterward.

Python programFileclose()finalize and releasewrite datafinish changes
How does data move from a Python program into a file, and what role does closing play?

Mistakes with File Operations

  • Common mistake

    Opening a file in write mode when existing content should remain

    What it looks like
    open("log.txt", "w")
    Why it fails

    Write mode erases existing file content.

    Do this instead

    Use append mode when the existing content must be preserved and new data added.

  • Common mistake

    Treating an empty string from readline() as a normal line

    What it looks like

    Continuing to request lines after readline() returns ""

    Why it fails

    An empty string signals that the end of the file has been reached.

    Do this instead

    Use the empty string as the condition that stops the reading process.

  • Common mistake

    Skipping close() after file operations

    What it looks like

    Opening and writing to a file without closing it

    Why it fails

    Changes may not be finalized, and the file may remain inaccessible to other processes.

    Do this instead

    Call f.close() or use a with statement for automatic closing.

  • Common mistake

    Confusing a returned line with the next file position

    What it looks like

    Assuming two readline() calls return the same line

    Why it fails

    Each readline() call advances through the file after returning a complete line.

    Do this instead

    Trace each call as returning the current line and moving the pointer to the next position.

Practice the File Cycle

MEDIUM

A file contains three lines. Describe what happens during three successive readline() calls, then describe the result of a fourth call. Finally, choose the safest mode for adding another line without removing the three existing lines.

Hints
  • Each readline() call returns one complete line and advances the file pointer.
  • At end-of-file, readline() returns an empty string.
  • Append mode preserves existing content.
Worked example

Tracing Four Reads

A file has exactly three available lines. What does each of four successive readline() calls represent?

  1. 1
    First call

    It returns the first complete line and advances the file pointer.

  2. 2
    Second call

    It returns the second complete line and advances again.

  3. 3
    Third call

    It returns the third complete line and reaches the end of the available content.

  4. 4
    Fourth call

    There is no more content, so readline() returns an empty string.

Result

The first three calls return lines; the fourth call returns an empty string that signals end-of-file.

Key Takeaways

  • Use open(filename, mode) to begin file operations.
  • Read mode retrieves content, write mode erases existing content before writing, and append mode preserves existing content while adding data.
  • readline() returns one complete line and advances the file pointer.
  • readline() returns an empty string at end-of-file, which can be used to stop a reading loop.
  • Close files with f.close() or use a with statement so changes are finalized and the file is released.

More concepts starting with W