python - 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。我成功地编写了一个新的文本文件,其中有选择地从以前的文本文件中收集了“内容”。
解决方案
如果以字符串形式存储书名的变量是,title
那么也许您应该在格式化您必须打开的文件的名称时将其作为参数传递:with open("{}.txt".format(title), 'w', encoding="utf8") as wrt:
推荐阅读
- javascript - 取 Firebase 数据库中数据集的平均值
- java - 读取输出时如何处理 Java Processes 的孙子?
- html - 输入字段设置为响应式
- javascript - 使用 css 自定义 bot 框架直线 API
- c# - 如何使用 Open XML SDK 在 Word 表格的空单元格中设置字体大小?
- angular - Angular 6:将数据保存到本地存储
- kubernetes - Prometheus 中 pod 内存利用率的自定义警报
- c# - 是否有任何可用于 Visual Studio 2017 的开放式封面工具或扩展?
- c++ - 在 Fedora 28 下使用 Eclipse CDT 中的 Clang
- r - 用 kable 或 DT 将标题固定在顶部