Solve the attributeerror ‘str’ object has no attribute ‘read’

Often times you will need to read the contents of external files such as text, csv, json and so forth. This post explains a common error that you might encounter when trying to those files from your Python development environment, be it PyCharm, VSCode, Jupyter and others.

Reproducing the str object has no read attribute error

Assume that you have a text or csv file in for file system which you want to read into your Python script. You might have tried to write code that might look similar to the snippet below:

 # define file location in file system
my_file = "C:\Temp\my_document.txt"  

# attempt to open your file for read purposes
with open (my_file, 'r') as f:
     my_file.read()

Python will raise an attribute error exception:

attributeerror 'str' object has no attribute 'read'

Here is a screenshot from Jupyter:

Solving the string read exception

Python allows to easily read and write the content of files. Whenever we attempt to open the file using the open function, Python returns a file object that has among others a read method. The problem with the code written above that we invoked the read method on the string containing the file name instead of invoking it on the file object.

How to correctly read a text or csv file?

my_file = "C:\Temp\my_document.txt"  

# opening a file returns a file object
with open (my_file, 'r') as f:
    # read the file object
    f.read()

Next Learning

How to correctly replace list elements in Python?