【发布时间】:2020-03-20 01:48:12
【问题描述】:
我有一个 Python 脚本,我认为应该:
- 打开文件
- 将其内容保存在变量中
- 对于变量中的每一行:
- 用正则表达式编辑它
- 将其附加到另一个变量
- 将第二个变量写入原文件
这是脚本的 MWE 版本:
# [omitting some setup]
with open(setFile, 'r') as setFile:
olddata = setFile.readlines()
newdata = ''
for line in olddata:
newdata += re.sub(regex, newset, line)
with open(setFile, 'w') as setFile:
setFile.write(newdata)
当我运行脚本时,出现以下错误:
Traceback (most recent call last):
File C:\myFolder\myScript.py, line 11, in <module>
with open(setFile, 'w') as setFile:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
据我所知,Python 抱怨接收 setFile 变量作为 open() 的参数,因为它不是预期的类型,但为什么它之前接受它(当我只阅读文件)?
我想我的错误很明显,但是由于我是 Python 的新手,所以我不知道它在哪里。谁能帮帮我?
【问题讨论】:
标签: regex python-3.x file typeerror