python - 如何在没有此错误的情况下获得正确的文件目录?
问题描述
所以我正在制作一个脚本来读取一堆文本文件(每首歌一个)作为歌词。它的工作原理是您输入一个歌词短语,脚本会扫描所有可用文件以查找这些歌词并告诉您歌曲的名称。问题是斜线不起作用。我更改了“/”和“\”之间的斜线,但我遇到了错误。
当我使用正斜杠时,我看到以下内容:
“OSError:[Errno 22] 无效参数:'C:/Users/[My Name]/Desktop/MusicLyricSearch/AllSongs/Old_Town_Road.txt'”
当我放回斜杠时,我得到了错误:
“SyntaxError:(unicode 错误)'unicodeescape'编解码器无法解码位置 3-4 中的字节:截断 \UXXXXXXXX 转义”。
我看过许多其他关于如何执行此操作的帖子,例如:在 多个文本文件中搜索两个字符串? 和 (unicode 错误)“unicodeescape”编解码器无法解码位置 2-3 中的字节:截断 \UXXXXXXXX 转义
所以,第一个链接实际上是代码,但我得到了错误
“SyntaxError:(unicode 错误)'unicodeescape'编解码器无法解码位置 3-4 中的字节:截断 \UXXXXXXXX 转义”
解决此问题的第二个链接也没有真正帮助
这是我的代码:
from os import listdir
lyricSearch = input("Input the phrase from the song: ")
with open("C:/Users/[My Name]/Desktop/MusicLyricSearch/AllSongs/results.txt", "w") as f:
for filename in listdir("C:/Users/[My Name]/Desktop/MusicLyricSearch/AllSongs"):
with open(" C:/Users/Traner/Desktop/MusicLyricSearch/AllSongs/" + filename) as currentFile:
lyrics = currentFile.read()
if(lyricSearch in lyrics):
f.write("The song is", filename)
else:
f.write("Error: Could not find lyrics in any songs")
我希望得到代码来改变我的代码来显示歌词的文件名,而不是我得到错误。
PS 正如你可能知道的那样,因为我基本上是复制代码,所以我对 python 编码还是很陌生。
解决方案
from os import listdir
lyricSearch = input("Input the phrase from the song: ")
with open(r"C:\Users\[My Name]\Desktop\MusicLyricSearch\AllSongs\results.txt", "w") as f:
for filename in listdir(r"C:\Users\[My Name]\Desktop\MusicLyricSearch\AllSongs"):
with open(r"C:\Users\Traner\Desktop\MusicLyricSearch\AllSongs\" + filename) as currentFile:
lyrics = currentFile.read()
if(lyricSearch in lyrics):
f.write("The song is", filename)
else:
f.write("Error: Could not find lyrics in any songs")
错误来自\U
编写时发生的错误\User
。这充当八字符 unicode 转义的开始,但由于您继续使用文件路径,python 无法解释该转义码并吐出错误。字符串开头的r
强制将其视为原始字符串,因此不考虑 unicode 转义。
推荐阅读
- c# - 获取系统亮度级别
- python - 从函数在数据框中创建多列
- asp.net-mvc - 如何在 asp.net mvc 部分视图中使用 Vue 组件 (*.vue)
- javascript - 加载应用程序时如何在角度应用程序中显示时间倒计时
- unix - 如何在扩展 unix 后获取所有内容
- batch-file - 计算名称以 )x 结尾的文件夹
- java - 如何在 OCC(commercewebservices)中正确使用我们的自定义订单?
- facebook-graph-api - 我如何使用 GraphQL Mutation?
- java - 登录后如何为每个用户动态更改图标
- java - 用于 REDIS 的 Spring Boot 反序列化 ResponseEntity