1

我正在编写一个函数,我的输入参数是文件路径:C:\Users\HP\Desktop\IBM\New 文件夹

def read_folder(pth):
    for fle in Path(pth).iterdir():
        file_name = Path(pth) / fle
    return file_name

为了我使用这个功能,我需要r''在文件路径中指定,即。

read_folder(r'C:\Users\HP\Desktop\IBM\New folder')

有没有一种方法可以避免r''在文件路径中指定,即。如下所示,代码将起作用。

read_folder('C:\Users\HP\Desktop\IBM\New folder')

我想这样做的原因是为了让用户更容易将目录路径复制并粘贴到函数中并运行函数。所以更多的是为了用户端的易用性。

非常感谢。

4

2 回答 2

1

You can't really do that because without prepending r to your string there's no way python interpreter would know that your string contains \ intentionally and not on purpose to escape the characters.

So you've to either use r"C:\Users\HP\Desktop\IBM\New folder" or "C:\\Users\\HP\\Desktop\\IBM\New folder" as argument while calling read_folder function.

于 2020-02-26T12:32:01.390 回答
0

您可以转义反斜杠:

read_folder('C:\\Users\\HP\\Desktop\\IBM\New folder')
于 2020-02-26T11:53:35.797 回答