VMware ESXi and vSphere Cluster Management
How to Read and Write Files in Python
Learn Python file handling with open(), read(), write(), append mode, context managers, file modes, and practical text-file examples.
What file handling means in Python
File handling is the process of creating, opening, reading, writing, appending to, and closing files. A file is a named collection of data stored on disk, such as notes.txt.
Python includes built-in support for basic text-file operations. You do not need to install a separate library to work with ordinary text files.
Python's built-in open() function returns a file object. A file object is the Python object that provides operations such as reading, writing, and closing a file.
Filename, path, and file object
- A filename is the name of a file, such as
notes.txt. - A path identifies where the file is located. It may be relative, such as
data/notes.txt, or absolute, such as a complete location on your operating system. - A file object is the value returned by
open()and usually assigned to a variable, such asfile_handle.
file_handle = open('notes.txt', 'r')In this example, notes.txt is the filename, 'r' is the mode, and file_handle refers to the returned file object.
Opening and creating files with open()
The basic syntax is:
open(filename, mode)The filename argument specifies which file to access. The mode argument specifies what you intend to do with it, such as read existing content, replace content, or add content at the end.
Assign the returned object to a descriptive variable so that you can use its methods:
file_handle = open('test.txt', 'w')A relative filename or path is resolved from Python's current working directory. This is the directory from which the Python process resolves relative paths. It is not always the same directory as the folder containing your script. This difference commonly explains why a newly created file seems to be missing.
Opening a nonexistent file in w mode or a mode can create the file. Opening a nonexistent file in r mode or r+ mode raises an error because those modes require an existing file.
Python text file modes
The mode controls both the allowed operations and what happens to existing content.
Read mode: r
Read mode retrieves data from an existing file:
file_handle = open('notes.txt', 'r')If the file does not exist at the requested path, Python raises FileNotFoundError.
Write mode: w
Write mode creates a file if necessary. If the file already exists, Python truncates it: its previous contents are removed before new text is written.
file_handle = open('notes.txt', 'w')Append mode: a
Append mode creates the file if it is missing and writes new text at the end when it already exists. Existing contents are not removed.
file_handle = open('activity.log', 'a')This mode is useful for log-like files, where each new entry should be preserved.
Read/write mode: r+
Read/write mode permits both reading and writing, but the file must already exist:
file_handle = open('notes.txt', 'r+')This mode begins at the start of the file. Reading and writing share the same current file position, so it requires more care than using separate read and write operations.
Writing text to a file
The file object's write() method stores a string in the file. It returns the number of characters written, although beginner programs usually do not need to use that return value.
Writing one message
file_handle = open('message.txt', 'w')
file_handle.write('Have a nice day!')
file_handle.close()The call to close() finishes the manual workflow. A preferred automatic-closing version appears later.
Multiple write() calls
file_handle = open('message.txt', 'w')
file_handle.write('First message')
file_handle.write('Second message')
file_handle.close()write() does not automatically add a line break. The resulting file may contain First messageSecond message on one line.
Use the newline escape sequence \n to begin a new line:
file_handle = open('message.txt', 'w')
file_handle.write('First message\n')
file_handle.write('Second message\n')
file_handle.close()The resulting text has two separate lines. Newline characters are part of the string being written, so add them wherever a line should end.
Overwriting an existing file
file_handle = open('message.txt', 'w')
file_handle.write('Only this text remains.\n')
file_handle.close()If message.txt already contained other text, opening it with w removed that old text before the new string was written. To preserve old content and add a new entry, use a instead:
file_handle = open('activity.log', 'a')
file_handle.write('A new activity occurred.\n')
file_handle.close()Closing files and cleaning up resources
An opened file uses an operating-system resource. Closing it releases that resource and helps ensure buffered output is flushed to disk. Buffering means Python or the operating system may temporarily hold output before writing it fully.
When manually opening a file, call close() after the work is complete:
file_handle = open('test.txt', 'w')
file_handle.write('Saved text.\n')
file_handle.close()Manual closing can be forgotten, and an error could occur before the close() call runs. Python's preferred pattern is a context manager: a with statement that automatically closes the file when its block ends, including when an error occurs inside the block.
with open('test.txt', 'w') as file_handle:
file_handle.write('Saved text.\n')The indented statements use the file while it is open. After the block finishes, the file is closed automatically.
Reading file contents
Read all content with read()
Open an existing text file in read mode and call read() to retrieve its contents as one string:
with open('test.txt', 'r') as file_handle:
contents = file_handle.read()
print(contents)The returned string includes the text in the file, including newline characters that were stored there.
File position and repeated reads
Reading starts at the file's current position. After read() reads all remaining content, the position is at the end of the file. Therefore, a second call usually returns an empty string:
with open('test.txt', 'r') as file_handle:
first_read = file_handle.read()
second_read = file_handle.read()
print(first_read)
print(repr(second_read)) # ''To read the content again, store the first result, reopen the file, or later learn to reset the position with seek().
Read one line at a time
A file object can be used directly in a for loop. Each iteration supplies the next line:
with open('test.txt', 'r') as file_handle:
for line in file_handle:
print(line, end='')Each line commonly already ends with \n. Using end='' prevents print() from adding a second newline. Without it, output may show an unwanted blank line between lines.
Reading everything versus reading line by line
read()is simple and convenient when the file is small enough to fit comfortably in memory.- Iterating with
for line in file_handleprocesses the file incrementally and is generally better for larger files.
Common file object methods and patterns
Safe beginner workflow
- Choose the correct file path and mode. Use
rto read,wto replace or create, andato add without removing existing text. - Open the file with
with open(...) as file_handle. - Read with
read()or iterate through lines, or write withwrite(). - Add
\nexplicitly when separate lines are needed. - Allow the
withblock to finish so the file closes automatically. - Verify the current working directory, expected filename, and final contents.
Write and then read a file
This example demonstrates the normal automatic-closing approach. The second with block reopens the file, so reading starts at the beginning.
with open('daily_note.txt', 'w') as file_handle:
file_handle.write('Study file handling.\n')
file_handle.write('Practice using a context manager.\n')
with open('daily_note.txt', 'r') as file_handle:
contents = file_handle.read()
print(contents)Troubleshooting file programs
The expected file cannot be found
A relative filename is resolved from the current working directory, which may differ from the script's directory. Check the directory from which the program was launched, then verify the filename and extension. Correct the relative path or use an explicit absolute path when appropriate.
FileNotFoundError appears in read mode
Read mode requires the file to exist at the requested path. Create it first, correct the path, or check the current working directory. Use w or a only when creating a missing file is intended.
Existing contents disappeared
The file was probably opened in w mode, which truncates existing content. Use a when adding new text, or r when only reading is needed. Back up important files before testing write operations.
Several writes appear on one line
Separate write() calls do not create line breaks. Add \n to the strings at the desired line boundaries.
Text is missing or changes are incomplete
With manual file handling, the file may not have been closed, or the program may have stopped before cleanup. Prefer a with open(...) block and check that the destination folder is writable.
A second read() returns an empty string
The first read moved the current file position to the end. Reopen the file, use the stored first result, or later learn to reset the position with seek().
Exam-relevant notes
open()returns a file object; it does not directly return the file's text.rrequires an existing file, whilewandacan create a missing file.wtruncates existing content;apreserves existing content and writes at the end.write()writes the supplied string exactly and does not add\nautomatically.with open(...) as file_handleis preferred because it closes the file automatically.read()begins at the current file position, so reading to the end leaves no remaining text for a second read.
For more advanced path operations, structured formats, encodings, and binary files, explore related topics such as Python file handling after mastering these basic text-file patterns.