python - os.startfile 在Python2上工作但在Python3上出现错误

标签 python python-3.x

所以我在 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/

相关文章:

python - 游戏过线不起作用。为什么它不能正确显示获胜和失败的比赛?

python - 如何使用 Python 和 web3.py 调用智能合约函数

python - eval(dir()[0]) 在 python 中做什么

python xlsxwriter @ 符号添加到公式中

python-3.x - 如何在 tensorflow 2.0b 中检查/释放 GPU 内存?

python - 异常 "There is no current event loop in thread ' MainThread'“在运行新循环时

Python Selenium : Is there a way to install webdriver inside the virtual enviroment

python-3.x - 如何在 fritzconnect 中发送 call_action

python - 进行可能的组合?

Python,类型错误 : unhashable type: 'list'