python调用shutil模块时输入的参数带‘r’表示的意义

比如以下的代码,在src和dst中都有r,代表什么意思呢?是不是就是原始字符串的意义?我不太确定。
import shutil

将a文件夹下的“a.xlsx”文件,移动到b文件夹中,并重新命名为“aa.xlsx”

src = r”C:/Users/黄伟/Desktop/publish/os模块/test_shutil_a\a.xlsx”
dst = r”C:\Users\黄伟\Desktop\publish\os模块\test_shutil_b\aa.xlsx”
shutil.move(src,dst)

Jason990420
最佳答案

在Python的string前面加上'r', 是为了告诉编译器这个string是个raw string,不要转义 backslash '\' 。 例如,'\n' 在raw string中,是两个字符,\n, 而不会转义为换行符。 由于正则表达式和\会有冲突,因此,当一个字符串使用了正则表达式后,最好在前面加上'r'


src = r"C:/Users/ 黄伟 / Desktop/publish/os 模块 /test_shutil_a\a.xlsx"
dst = r"C:\Users\ 黄伟 \Desktop\publish\os 模块 \test_shutil_b\aa.xlsx"

等同

src = "C:/Users/ 黄伟 / Desktop/publish/os 模块 /test_shutil_a\\a.xlsx"
dst = "C:\\Users\\ 黄伟 \\Desktop\\publish\\os 模块 \\test_shutil_b\\aa.xlsx"
1年前 评论
讨论数量: 2
Jason990420

在Python的string前面加上'r', 是为了告诉编译器这个string是个raw string,不要转义 backslash '\' 。 例如,'\n' 在raw string中,是两个字符,\n, 而不会转义为换行符。 由于正则表达式和\会有冲突,因此,当一个字符串使用了正则表达式后,最好在前面加上'r'


src = r"C:/Users/ 黄伟 / Desktop/publish/os 模块 /test_shutil_a\a.xlsx"
dst = r"C:\Users\ 黄伟 \Desktop\publish\os 模块 \test_shutil_b\aa.xlsx"

等同

src = "C:/Users/ 黄伟 / Desktop/publish/os 模块 /test_shutil_a\\a.xlsx"
dst = "C:\\Users\\ 黄伟 \\Desktop\\publish\\os 模块 \\test_shutil_b\\aa.xlsx"
1年前 评论
chowjiawei

让我猜猜 你叫 黄伟

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!