【问题标题】:How can i get the correct file directory without this error?如何在没有此错误的情况下获得正确的文件目录?
【发布时间】:2019-05-06 02:23:18
【问题描述】:

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

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

"OSError: [Errno 22] 无效参数:' C:/Users/[My 名称]/Desktop/MusicLyricSearch/AllSongs/Old_Town_Road.txt'"

当我放回斜杠时,我得到了错误:

"SyntaxError: (unicode error) 'unicodeescape' 编解码器无法解码字节 在位置 3-4:截断 \UXXXXXXXXXX 转义”。

我看过很多其他关于如何做到这一点的帖子,例如: Searching multiple text files for two strings?(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

所以,第一个链接确实是代码,但我得到了错误

"SyntaxError: (unicode error) '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")

我希望得到代码来更改我的代码以显示歌词的文件名,而不是我得到错误。

附:正如你可能知道的那样,因为我基本上是复制代码,所以我对 python 编码还是很陌生。

【问题讨论】:

  • 使用正斜杠但省略C: 之前的空格。如果还没有完成,你应该通过Python tutorial
  • 尝试使用反斜杠,但在字符串前添加r。当您键入 user 时,\U 被处理为八字符 unicode 转义码的开头。像这样的东西: open(r'C:\Users[My Name]\Desktop\MusicLyricSearch\AllSongs\results.txt', "w")

标签: python directory


【解决方案1】:
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 转义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 2015-10-09
    • 1970-01-01
    相关资源
    最近更新 更多