使用户名独立 os.rename

Making username-independent os.rename

我正在为我的朋友制作一个模块,它在编码方面基本上一无所知,所以我有一个 setup.py 可以将下载文件夹中的东西放到项目需要的文件夹中是在。但是,我的朋友不知道他们的计算机用户名,所以我用 os.getlogin(),但是当我尝试将我赋值的变量放入文件路径时,它会出现多个错误。

这是我当前的代码:

import os

user = os.getlogin()

os.rename(r"C:\Users\"" + user + "\FILEPATH\FILEPATH\FILENAME", r"C:\Users\"" +
         user +"\FILEPATH\FILEPATH\FILENAME")

你的代码 r"C:\Users\"" 有问题。

>>> path_prefix
'C:\Users\"'

From the documentation:

Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the literal, not as a line continuation.

您可以将 f-strings 与原始字符串结合使用以避免您遇到的问题:

import os

user = os.getlogin()

os.rename(
    fr"C:\Users\{user}\old\path",
    fr"C:\Users\{user}\new\path",
)

您还可以使用 os.path.expanduser 获取用户的主目录:

import os

home = os.path.expanduser("~")

os.rename(
    fr"{home}\old\path",
    fr"{home}\new\path",
)

话虽如此,使用 os.path.join 似乎是一种更合适的连接路径方式,同时避免与 + 运算符连接并处理原始字符串 and/or 反斜杠:

import os

home = os.path.expanduser("~")

os.rename(
    os.path.join(home, "old", "path"),
    os.path.join(home, "new", "path"),
)