首页 > 解决方案 > OSError:[Errno 22] 无效参数:'The Game (John 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), 'w', encoding="utf8") as wrt:
                wrt.write(content)
                wrt.close

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

标签: pythonfilenameserrnooserror

解决方案


如果以字符串形式存储书名的变量是,title那么也许您应该在格式化您必须打开的文件的名称时将其作为参数传递:with open("{}.txt".format(title), 'w', encoding="utf8") as wrt:


推荐阅读