Python OSError:[Errno 22]无效参数:';游戏(约翰·史密斯)\n.txt';

Python OSError:[Errno 22]无效参数:';游戏(约翰·史密斯)\n.txt';,python,filenames,errno,oserror,Python,Filenames,Errno,Oserror,第37行: OSError:[Errno 22]无效参数:“游戏(约翰·史密斯)\n.txt” 我试图写文件,并根据书名命名。我相信我会因为标题中的“\n”而出现上述错误,我已尝试删除它,但没有成功。下面是生成错误的代码部分 #Convert book title into string title = str(cb) title.replace("\n",'') title.strip() #write

第37行:

OSError:[Errno 22]无效参数:“游戏(约翰·史密斯)\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就被定义。我成功地编写了一个新的文本文件,其中的“内容”是从以前的文本文件中选择性地收集的。

如果您使用的是
replace
,而没有将其分配给变量,请记住
strip
replace
不会就地更改变量。这应该起作用:

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

如果以字符串形式存储书籍标题的变量是
title
,那么在格式化必须打开的文件名时,可能应该将该变量作为参数传递:
,并将open({}.txt).format(title),'w',encoding=“utf8”)作为wrt:

字符串
.replace()
函数不修改现有字符串;它返回一个新字符串。因此,您需要执行
title=title.replace(“\n”,”)
title = title.replace("\n",'')
title = title.strip()
with open(f"{title}.txt", 'w', encoding="utf8") as f:
    f.write(content)