Regex 试图用Python以写模式打开文件时出现Getting TypeError()错误
我有一个Python脚本,在我看来应该:Regex 试图用Python以写模式打开文件时出现Getting TypeError()错误,regex,python-3.x,file,typeerror,Regex,Python 3.x,File,Typeerror,我有一个Python脚本,在我看来应该: 打开一个文件 将其内容保存在变量中 对于变量中的每一行: 用正则表达式编辑它 将其附加到另一个变量 将第二个变量写入原始文件 以下是该脚本的MWE版本: # [omitting some setup] with open(setFile, 'r') as setFile: olddata = setFile.readlines() newdata = '' for line in olddata: newdata += re.su
# [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
回溯(最近一次呼叫最后一次):
文件C:\myFolder\myScript.py,第11行,在
打开(setFile,'w')作为setFile:
TypeError:应为str、bytes或os.PathLike对象,而不是_io.TextIOWrapper
据我所知,Python抱怨将setFile
变量作为open()
的参数接收,因为它不是预期的类型,但为什么它以前接受它(当我只读取文件时)
我想我的错误很明显,但由于我是Python新手,我无法找到它在哪里。有人能帮我一个忙吗?只是想知道为什么在文件中使用相同的变量名,然后作为filehandler,然后在下一个with函数中使用相同的变量名 _io.TextIOWrapper是上一次打开的对象,已关联到setFile变量。 尝试:
只是想知道为什么在文件中使用相同的变量名,然后作为filehandler,然后在下一个with函数中使用相同的变量名 _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)