python - 在文件路径中读取时从字符串文字更改为原始字符串文字的替代方法
问题描述
我正在编写一个函数,我的输入参数是文件路径: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')
我想这样做的原因是为了让用户更容易将目录路径复制并粘贴到函数中并运行函数。所以更多的是为了用户端的易用性。
非常感谢。
解决方案
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.
推荐阅读
- python - WSL2:Python 使用 VS Code 调试器重命名文件
- php - MySQL 服务器已消失 - 数据包乱序。预期 0 收到 1. 数据包大小=72
- php - 如何在 laravel 8 中使用(路由)传递 slug 的参数?
- charts - ChartJS - 如何选择可见的数据标签
- c# - 带有 Web 和 GUI 项目的 C# 解决方案
- c - 如何打印结构的字段
- php - 链接缩短服务 API 返回 Null
- javascript - javascript - 在再次调用之前取消等待的函数
- c - 缓冲区处理如何导致不同的行为?
- javascript - 在卸载 javascript 之前等待函数执行