Concepts / Working with Strings in Python

Working with Strings in Python

Files are opened using open(filename, mode), where mode controls read/write/append permissions and what happens to existing data.

  • Programming

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.

creates accessfinish operationOpen filefilename and modeRead or writefile operationClose filefinalize and release
How does information move between a Python program and a file?

Choosing an Opening Mode

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
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.

f = open("poem.txt", "r") line_one = f.readline() line_two = f.readline() line_three = f.readline() f.close()

readline() advancesreadline() advancesno more contentLine 1first returned lineLine 2next returned lineLine 3next returned lineEOFempty string
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
line returnedrequest next lineno content remainsend conditionreadline()request a lineComplete linecontinue readingEmpty stringend-of-fileStop readingclose file
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.

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

Mistakes with File Operations

  • Opening a file in write mode when existing content should remain

    Write mode erases existing file content.

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

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

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

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

  • Skipping close() after file operations

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

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

  • Confusing a returned line with the next file position

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

    Fix: 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.

Tracing Four Reads

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

First call: It returns the first complete line and advances the file pointer.

Second call: It returns the second complete line and advances again.

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

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

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.