regex - Getting TypeError trying to open() a file in write mode with Python
问题描述
I have a Python script that in my mind should:
- Open a file
- Save its content in a variable
- For each line in the variable:
- Edit it with a regular expression
- Append it to another variable
- Write the second variable to the original file
Here is a MWE version of the script:
# [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)
When I run the script I get the following error:
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
As far as I can understand, Python is complaining about receiving the setFile
variable as an argument of open()
because it isn't of the expected type, but then why did it accept it before (when I only read the file)?
I suppose that my mistake is quite evident but, as I am a neophyte in Python, I can't find out where it is. Could anyone give me a help?
解决方案
只是好奇为什么你为你的文件使用相同的变量名,然后作为你的文件处理程序,然后在你的下一个 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)
推荐阅读
- flutter - 使用不包含“BlocName”的上下文调用 BlocProvider.of()
- c - 双向链表实现显示 C 中的分段错误
- python - 从python中的对象创建gui的字符串列表
- ruby-on-rails - Rails:AJAX Datatables 按钮打开 Modal
- python-3.x - PyInstaller ModuleNotFoundError --paths 标志似乎不起作用
- python - 如何确定从 txt 文件中读取项目的频率并打印项目名称以及项目出现的次数?
- node.js - 部署时不显示数据
- xcode - 通过同一文件内但结构外的函数更改状态
- handlebars.js - 如何将参数传递给 Handlebars 中的嵌套子项
- github - 将请求从一个存储桶推送到另一个存储桶