【问题标题】:Getting TypeError trying to open() a file in write mode with Python尝试使用 Python 以写入模式打开()文件时出现 TypeError
【发布时间】:2020-03-20 01:48:12
【问题描述】:

我有一个 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 的新手,所以我不知道它在哪里。谁能帮帮我?

【问题讨论】:

    标签: regex python-3.x file typeerror


    【解决方案1】:

    只是好奇为什么你在你的文件中使用相同的变量名,然后作为你的文件处理程序,然后在你的下一个函数中再次使用。

    _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)
    

    【讨论】:

    • 好吧,老实说,这只是懒惰。所以,正如我所料,我的错误是非常愚蠢的。非常感谢!
    • 懒惰是我大部分编程的根源
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多