OSError:[Errno 22]无效的参数:'The GameJohn Smith\ n.txt'

问题描述

第37行:

  with open("{}.txt".format(cb),'w',encoding="utf8") as wrt:

OSError:[Errno 22]无效的参数:'The Game(John Smith)\ n.txt'

我正在尝试编写文件并根据书名命名。我相信由于标题中的“ \ n”,我得到了上面的错误,我试图删除它,但没有运气。这是代码中产生错误的部分

#Convert book title into string
            title = str(cb)
            title.replace("\n",'')
            title.strip()
#write the book notes in a new file
            with open("{}.txt".format(cb),encoding="utf8") as wrt:
                wrt.write(content)
                wrt.close

我知道这是错误的出处,因为如果给文件命名,它就可以正常工作。 cb只是当前书的变量,它等于列表值,一旦列表值与从文本文件读取的行匹配,就定义cb。我成功编写了一个新的文本文件,该文件的“内容”是从先前的文本文件中选择性收集的。

解决方法

如果以字符串形式存储书名的变量为title,那么在格式化必须打开的文件名时,也许应该将其作为参数传递:{{1} }

,

您在使用replace而不将其分配给变量时,请记住stripreplace不会在适当位置更改变量。这应该起作用:

title = title.replace("\n",'')
title = title.strip()
with open(f"{title}.txt",'w',encoding="utf8") as f:
    f.write(content)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...