python - 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 文件时它工作正常
我真的不知道错误消息是什么意思,我该如何解决?
解决方案
to 的参数open()
必须是一个文件名,而不是包含多个文件名的元组。
如果要读取所有文件,请循环执行:
for filename in filenames:
with open (filename, encoding = 'utf8') as f_obj:
contents = f_obj.read()
print(contents)
推荐阅读
- scala - 为什么我不能在我的程序中使用 UpdateStateByKey?
- scipy - scipy.linalg.lu() 与 scipy.linalg.lu_factor()
- html - 居中的文本和对齐
- python - Pandas:如果其中任何行包含特定值,我如何删除具有相同唯一 ID 的任何行
- node.js - tsc(TypeScript 编译器)和 ts-node 有什么区别?
- php - 如何通过比较 php 中的多个值来删除和重新索引数组重复?
- python - 如何从 django 模型中获取数据
- apache-pig - Apache pig:如何将 ignoreBadFiles 标签与加载功能一起使用?
- c++ - 具有空值的 C++ 二叉搜索树级顺序
- javascript - Javascript 数组仅运行函数,该函数在数组的一个元素上返回一个承诺