Reading & Writing Text Files
Once a file is opened with the correct mode, you can start interacting with its content. For text files, Python offers a variety of intuitive methods for both writing data into the file and reading data out of it.
Writing to Text Files
When you open a file in write ('w'), append ('a'), or exclusive creation ('x') mode, you can add string data to it.
The write() Method
The .write(string) method is the most fundamental way to write data. It takes a single string argument and writes it to the file.
The .write() method returns the number of characters written, which can be useful in some advanced scenarios, but is often ignored in common usage.
Pyground
Create a file named `greetings.txt` and write a simple message to it.
Expected Output:
Wrote two lines to greetings.txt
Output:
You Must Add Newlines!
The .write() method does not automatically add a newline character (\n) at the end of the string. You must include it manually if you want to start the next write on a new line.
The writelines() Method
The .writelines(list_of_strings) method is used to write all strings from an iterable (like a list) to the file. It’s like calling .write() for every item in the list.
Pyground
Write a list of grocery items to a file named `groceries.txt` using `writelines()`.
Expected Output:
Grocery list saved.
Output:
Just like .write(), the .writelines() method does not add newline characters between the items. You must ensure the newlines are already part of the strings in your list, as shown in the example above.
Reading from Text Files
Reading from files is just as important, and Python gives you several methods to control exactly how you retrieve the data. This is important because reading an entire massive file into memory can be inefficient.
Let’s create a sample file to work with for the following examples:
Pyground
Create a file named `poem.txt` that we can use for the reading examples below.
Expected Output:
poem.txt has been created.
Output:
Now, let’s explore the different ways to read from poem.txt.
read(size=-1): Read the Whole File
- Action: Reads from the file until the end of the file (EOF) is reached.
- Returns: A single string containing the entire file content.
sizeparameter: If you provide an optional integersize, it will read that many characters.- Memory: Be careful! Using
.read()on a very large file can consume a lot of memory as it loads the whole file at once.
Pyground
Read the entire content of `poem.txt` into a single string.
Expected Output:
--- File Content ---\nThe road goes ever on and on,\nDown from the door where it began.\nNow far ahead the road has gone,\nAnd I must follow, if I can.\n\nType of content: <class 'str'>
Output:
The File Pointer: seek() and tell()
Python keeps track of your position in a file using an internal pointer. When you read or write, this pointer moves. You can also manipulate it manually.
tell(): Returns the current position of the pointer (as an integer number of bytes from the beginning of the file).seek(offset, whence=0): Moves the pointer to a new location.offset: The number of bytes to move.whence: The reference point.0(default) for the beginning of the file,1for the current position, and2for the end of the file.
Pyground
Demonstrate using `tell()` and `seek()` to read specific parts of a file.
Expected Output:
Initial pointer position: 0\nRead 10 bytes: 'The road g'\nPointer position now: 10\nPointer moved to: 33\nRead from new position: 'where it began.'
Output:
Manual pointer management with seek() is powerful but can be complex. For text files, it’s often easier to read the data and process it sequentially. seek() is more commonly used when working with fixed-size records in binary files.