Working With Files In Python
1. READING TEXT FROM A FILE
In this section, we will learn different methods to load a file into the program.
1.1. Reading an Entire File
In the following example, we open a file (.txt format) that contains first paragraph of the book,Alice in the Wonderland. You can download the whole text here After opening, we will print its content:
first, we defined the path to the file and stored it in the variable
file_name
open()
function needs one argument: the name of the file we want to open. Theopen()
function returns an object representing the file. In our example,open(file_name)
returns an object representingalice_3p.txt
. Python stores this infile_object
, which we’ll work with later in the programnotice how we call
open()
in this program but notclose()
because the keywordwith
closes the file automatically once it is no longer neededwe used the
read()
method to read the entire contents of the file and store it as one long string in the variable,content
when we
print
the value ofcontent
, we get the entire text file back:
File path:
Relative File Path: In the above example,
alice_3p.txt
file is present in the same folder from where this program is stored so we provided a relative file path — a relative file path tells Python to look for the specified file in a location relative to the directory where the currently running program file is stored.Absolute File Path: We can also tell Python the exact location of the file iregardless of where the program that’s being executed is stored. This is called an absolute file path
1.2. Reading Line by Line
We can use a for
loop on the file_object
to examine each line from the file:
Here is the output:
These blank lines appear because an invisible newline character() is at the end of each line in the text file. We can use the strip()
method to remove the blank lines
1.3. Making a List of Lines from a File
In the above example, we did use for
loop to print each line in the file but what if we need this list of lines (content of file) outside the with
block? When we use with
, the file object returned by open()
is only available inside the with
block that contains it. If we want to access the file’s contents outside the with
block, we can store the content in a list
inside the with
block and then work with that list
later:
Notice that we used the
readlines()
method to store the text lines as alist
as compared toread()
method, which stores the entire content as astring
.secondly, we
print
thelist
as whole, inside thewith
block, ANDprint
each item inside thelist
using afor
loop outside thewith
block Here is the output:
now you can see why there is a blank line — the presence of new line character () at end of each line, except the last one.
NOTE: When Python reads from a text file, it interprets all text in the file as a string. Therefore, if our text file contains numerical data, we have to convert it to an integer using the
int()
function or convert it to a float using thefloat()
function.
1.4. Working with File’s Contents
Example 1: Wrapping content into single line
Let suppose that after we store each line of the text file inside a list
using readlines()
method, we want to display the content in single line rather the line breaks included.
Output would be:
we have used the strip() method to remove all the blank lines
Example 2: Checking if your birthdate is within 1 million pi digits
In this example, we have used a file that contains the pi first 1 million digits after decimal place. To work with this in interesting manner, let’s write program to check whether someone birthday is within these 1 million digits.
Example 3: Replacing a word with another
Let suppose, we have text file that contains the topics that we have learned in Python (one topic on each line, ending with … in Python) We can use the replace()
method to replace all instances of Python
with Py
.
Output:
2. WRITING TEXT TO A FILE
To write any text to a file, we need to use
open()
with a two arguments — the first argument is still the name of the file where we want to write and the second argument,w
tells Python that we want to open the file in write mode.
We can open a file in read mode
r
, write modew
, append modea
, or mode that allows to both read and write to the filer+
If we omit the mode argument, Python opens the file in read-only mode by default.
NOTE: Python write strings to a text file, by default. If we want to store numerical data in a text file, we will have to convert the data to numerical format first using the int()
function
2.1. Writing to an Empty File
Let suppose we want to create a new file welcome.txt
and store a single string, Welcome to all guests
The open()
function automatically creates the file we’re writing to if it doesn’t already exist.
Writing multiple lines
We can write()
as many lines as we wish. For example:
2.2. Appending to a File
When we open a file in append a
mode, Python doesn’t erase the file before returning the file object. Therefore, all content we append will be added at the end of the file. Besides, just we studied above, if the file doesn’t exist, Python will create an empty file for us, before appending the content. Let’s append another line to the above file, welcome.txt
3. JSON DATA
In the following section we will work with json
module. To read more about the json data structure, please visit this link
3.1. Storing and Retrieving JSON Data
In Python, we store data using json.dump()
, and then load the dat into program using json.load()
a. Store the data
The json.dump()
function takes two arguments: a piece of data to store and a location where to store the data. Here is an example:
we first
import
thejson
module, to make the program work with json data typethen we ask the user to provide the username and store it inside the variable
username
then we provide the location of file path to store the data,
filename
then we open the file in write mode
w
and store it insidefile_object
then using
json.dump()
function we store the data in the file. The first argument is location to store the data and second argument is data itself
b. Retrieve the data
We use the json.load()
to load the data stored inside given file back into program
Last updated
Was this helpful?