我将非常有用的OS库用于IT自动化。
使用下面的代码创建文件夹/移动到文件夹/创建文件
import os
# create a directory
os.mkdir("directory")
# get the path of the directory
path = os.path.abspath("directory")
print(f"path after creating the directory: {path}")
# change current directory
os.chdir("directory")
path = os.path.abspath("directory")
print(f"path after changing current directory: {path}")
# create a file
with open("hello.py", "w"):
pass
输出量:
创建目录后的路径:P:\ Code \ Python \ directory
更改当前目录后的路径:P:\ Code \ Python \ directory \ directory
我听不懂:
为什么目录文件的路径正在更改?
我在\ directory中没有任何目录
感谢您的回答
如果您阅读了[abspath][1]
功能的文档,您将会理解为什么还会出现额外的directory
。
返回路径名路径的标准化绝对化版本。在大多数平台上,这等效于按如下方式调用函数normpath():normpath(join(os.getcwd(),path))。
[基本上,os.path.abspath('directory')
给您“当前目录(也恰好称为“目录”)中名为“目录”的内容的绝对路径为“]]
您所看到的绝对路径是您刚创建的目录中某些内容的尚不存在的绝对路径。您创建的目录的绝对路径保持不变,您可以使用以下方法进行检查:
os.path.abspath('.') # . -> current directory, is the one you created