em4995
em4995

Reputation: 77

TypeError: expected str, bytes or os.PathLike object, not tuple. How to solve?

I am trying to get this program to open and read two txt files I have made called cats.txt and dogs.txt

filenames = 'cats.txt', 'dogs.txt'
with open (filenames, encoding = 'utf8') as f_obj:
    contents = f_obj.read()
    print(contents)

But I keep getting this error message

TypeError: expected str, bytes or os.PathLike object, not tuple

But it works fine when I only do it with one of the txt files

I don't really know what the error message means and how can I solve it?

Upvotes: 2

Views: 30552

Answers (2)

kojiro
kojiro

Reputation: 77099

When you use a comma to separate two things in Python, you might* be creating a tuple.

>>> x=1
>>> type(x)
<class 'int'>
>>> x=1, 2
>>> type(x)
<class 'tuple'>

This is even true if you use a comma after one thing:

>>> x='hi',
>>> type(x)
<class 'tuple'>

Tuples are objects, like everything else, and a function expecting a string can't necessarily handle a tuple. But you can loop over a tuple and handle one string at a time.

for filename in filenames:
    with open(filename) as f:
        ...

*(You might be creating a tuple, but you will certainly be creating an iterable of some kind. If you surround the expression with square or curly braces, you'll create a list or a set, but not necessarily a tuple.)

Upvotes: 3

Barmar
Barmar

Reputation: 780899

The argument to open() has to be one filename, not a tuple with multiple filenames in it.

If you want to read all the files, do it in a loop:

for filename in filenames:
    with open (filename, encoding = 'utf8') as f_obj:
        contents = f_obj.read()
        print(contents)

Upvotes: 5

Related Questions