首页 > 解决方案 > 在文件路径中读取时从字符串文字更改为原始字符串文字的替代方法

问题描述

我正在编写一个函数,我的输入参数是文件路径: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')

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

非常感谢。

标签: pythonfilepathstring-literalsrawstring

解决方案


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.


推荐阅读