遇到TypeError尝试使用Python以写入模式打开()文件

我有一个Python脚本,在我看来应该:

  1. 打开文件
  2. 将其内容保存在变量中
  3. 对于变量中的每一行:
    1. 使用正则表达式对其进行编辑
    2. 将其附加到另一个变量
  4. 将第二个变量写入原始文件

这是脚本的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的新手,所以我找不到它的位置。有人可以帮我吗?

yanlovey 回答:遇到TypeError尝试使用Python以写入模式打开()文件

很好奇为什么在文件中使用相同的变量名,然后在文件处理程序中使用相同的变量名,然后在下一个具有功能的函数中再次使用。

_io.TextIOWrapper是您先前打开的对象,已分配给setFile变量。 尝试:

with open(setFile,'r') as readFile:
    olddata = readFile.readlines()
newdata = ''
for line in olddata:
    newdata += re.sub(regex,newset,line)
with open(setFile,'w') as writeFile:
    writeFile.write(newdata)
本文链接:https://www.f2er.com/3040872.html

大家都在问