首页 > 解决方案 > TypeError:预期的 str、字节或 os.PathLike 对象,而不是元组。怎么解决?

问题描述

我正在尝试让这个程序打开并读取我制作的两个 txt 文件,分别称为cats.txt 和 dogs.txt

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

但我不断收到此错误消息

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

但是当我只使用其中一个 txt 文件时它工作正常

我真的不知道错误消息是什么意思,我该如何解决?

标签: python

解决方案


to 的参数open()必须是一个文件名,而不是包含多个文件名的元组。

如果要读取所有文件,请循环执行:

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

推荐阅读