首页 > 解决方案 > Getting TypeError trying to open() a file in write mode with Python

问题描述

I have a Python script that in my mind should:

  1. Open a file
  2. Save its content in a variable
  3. For each line in the variable:
    1. Edit it with a regular expression
    2. Append it to another variable
  4. 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?

标签: regexpython-3.xfiletypeerror

解决方案


只是好奇为什么你为你的文件使用相同的变量名,然后作为你的文件处理程序,然后在你的下一个 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)

推荐阅读