通常情况下,我们在使用 Python 创作程序时,如果要将文件保存到特定的路径中,我们会使用类似于以下的代码:
import os
file_path = os.path.join('/Users', 'username', 'Documents', 'file.txt')
with open(file_path, 'w') as file:
file.write('Hello World!')
在上面的例子中,我们将文件保存到了 macOS 操作系统下的 /Users/username/Documents
目录中。但是这样的写法中我们要明确指定用户名,有时候在不同的机器和不同的操作系统下用户名可能会不一样,因此我们需要一种更加灵活的方法来指定目录路径。
我们可以使用 ~
符号代表当前用户的 home 目录,例如:
import os
file_path = os.path.join('~', 'Documents', 'file.txt')
file_path = os.path.expanduser(file_path)
with open(file_path, 'w') as file:
file.write('Hello World!')
在上面的代码中,我们使用了 ~
符号来代表当前用户的 home 目录,并使用了 os.path.expanduser()
方法将 ~
符号扩展为实际的目录路径。这样就可以灵活地保存文件路径了。