os.rename 移动文件

os.rename to move a file

我正在尝试创建一个程序,将其自身复制到另一个目录以备后用。它在我的 Windows 7 机器上工作正常,但是由于某种原因我收到以下错误消息。

WindowsError: [Error 3] The system cannot find the path specified

我已经使用 py2exe 将其编译为可执行文件。不管怎样,这是我的代码:

home = os.path.expanduser("~")
installPath = home + "\Logs"
copyPath = installPath + "\Keylogger.exe"

def installExe(copyPath):
    if not os.path.exists(copyPath):
        path = os.getcwd()
        path = os.path.join(path, "Keylogger.exe")
        os.rename(path, copyPath)

打印 copyPath 并手动检查它是否存在 - 它看起来合理吗? 例如那些反斜杠"\Keys""\Keylogger.exe" 是问题 在 python 字符串语法中它们被称为转义序列,因此与后面的字符变成单个字符。有关更多信息,请参阅文档,例如https://docs.python.org/2.0/ref/strings.html

创建路径的正确且可靠的方法是使用 os.path.join():

home = os.path.expanduser("~")
installPath = os.path.join( home, "Logs" )
copyPath = os.path.join( installPath, "Keylogger.exe" )