首页 > 解决方案 > 如何在没有此错误的情况下获得正确的文件目录?

问题描述

所以我正在制作一个脚本来读取一堆文本文件(每首歌一个)作为歌词。它的工作原理是您输入一个歌词短语,脚本会扫描所有可用文件以查找这些歌词并告诉您歌曲的名称。问题是斜线不起作用。我更改了“/”和“\”之间的斜线,但我遇到了错误。

当我使用正斜杠时,我看到以下内容:

“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 编码还是很陌生。

标签: pythondirectory

解决方案


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 转义。


推荐阅读