在复制文件对象路径的时候,Windows系统会在复制的路径前面加上肉眼看不到的奇怪信息,这个信息用Python打印出来是“\u202a”。

我们要使用真正的路径,当然要去掉这个看不见的“u202a”字符。目前我在CSDN找到的所有解决方案都是让开发者手动删除“\u202a”,这显然不方便,经过资料查找与测试,我找到了解决方案如下:

使用 path.strip(“\‪u202a”) 删除“\u202a”,即:

1
2
Path = r'‪C:\Users\114514\Jupyter\114514.html'
Path = Path.strip("\\‪u202a") #删除“\u202a”

示例:

1 不处理“\u202a”的代码片段:

1
2
3
Path = r'‪C:\Users\114514\Jupyter\114514.html'
#Path = Path.strip("\\‪u202a") #不删除“\u202a”
HtmlFile = open(r''+Path, 'r', encoding='utf-8')

运行后报错:

1
[Errno 22] Invalid argument: '\u202a‪C:\\Users\\114514\\Jupyter\\114514.html'

2 将“\u202a”删除的代码片段:

1
2
3
Path = r'‪C:\Users\114514\Jupyter\114514.html'
Path = Path.strip("\\‪u202a") #删除“\u202a”
HtmlFile = open(r''+Path, 'r', encoding='utf-8')

将HtmlFile打印,发现已经可以正常输出。

参考资料

Pycharm文件路径复制报错Invalid argument: ‘\u202a…原因及解决_HolenWu的博客-CSDN博客 python读取文件报错OSError: [Errno 22] Invalid argument: ‘\u202aC:\Users\yyqhk\Desktop\1.csv’_stone9159的专栏-CSDN博客 https://stackoverflow.com/questions/49267999/remove-u202a-from-python-string

本文于2021-05-14首发于Python路径中出现\u202a的解决方法(不用手工删除)_生化环材-CSDN博客