首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在没有此错误的情况下获得正确的文件目录?

如何在没有此错误的情况下获得正确的文件目录?
EN

Stack Overflow用户
提问于 2019-05-06 02:23:18
回答 1查看 67关注 0票数 0

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

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

“Name/Desktop/MusicLyricSearch/AllSongs/Old_Town_Road.txt'”:Errno 22无效参数:‘C:/User/My OSError

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

"SyntaxError:(unicode错误)‘独角形转义’编解码器无法解码位置3-4的字节:截断\UXXXXXXXX转义“。

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

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

"SyntaxError:(unicode错误)‘独角形转义’编解码器无法解码位置3-4的字节:截断\UXXXXXXXX转义“

修复这个问题的第二个链接也没有真正的帮助

这是我的密码:

代码语言:javascript
复制
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的编码非常陌生。

EN

回答 1

Stack Overflow用户

发布于 2019-05-06 03:00:58

代码语言:javascript
复制
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。这充当了8个字符unicode转义的开始,但是由于您继续使用文件路径,python无法解释该转义代码并发出错误。字符串开头的r强制将其视为原始字符串,因此不考虑unicode转义。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55998074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档