所以我在 Py2 上编写了一些快速代码,它使用 os 和 time 模块,每 3 秒打开一张图片,总共 5 次,它在 Py2 上完美运行,但在 Py3 上给出了一个错误,这对我没有任何解释.
此处错误:
(unicode 错误)“unicodeescape”编解码器无法解码位置 2-3 中的字节:截断\UXXXXXXXX 转义
这是代码:
import os
import time
times = 5
count = 0
print("This program has started")
while(count <= times):
time.sleep(3)
os.startfile("C:\Users\...\Picture.png") # Truncated
count += 1
else:
print("Program has finished")
最佳答案
Python 3 希望将 C:\Users
中的 \Uxxxx
序列视为 unicode 字符。在处理 Windows 路径(及其反斜杠)时,使用 raw strings 总是一个好主意。 ,它将把反斜杠视为普通字符:
os.startfile(r"C:\Users\...\Picture.png")
或者,您可以单独转义反斜杠:
os.startfile("C:\\Users\\...\\Picture.png")
关于python - os.startfile 在Python2上工作但在Python3上出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558444/