Python如何检查一个目录是否存在,如果不存在就创建它,并将图表存到新目录中?
Python如何检查一个目录是否存在,如果不存在就创建它,并将图表存到新目录中?
这个问题已经有答案了:
因此,我希望它独立于使用代码的计算机,所以我想能够在当前目录中创建一个目录并将我的图形保存到那个新文件中。我查看了一些其他问题,并尝试了这个(我有两个尝试,其中一个被注释掉了):
import os from os import path #trying to make shift_graphs directory if it does not already exist: if not os.path.exists('shift_graphs'): os.mkdirs('shift_graphs') plt.title('Shift by position on '+str(detector_num)+'-Detector') #saving figure to shift_graphs directory plt.savefig(os.path.join('shift_graphs','shift by position on '+str(detector_num)+'-detector')) print "plot 5 done" plt.clf
我得到了错误:
AttributeError: 'module' object has no attribute 'mkdirs'
我还想知道我的保存目录的想法是否可行,但由于上面部分中的错误,我没有能够测试它。
admin 更改状态以发布 2023年5月22日
您正在寻找以下内容之一:
os.mkdir
或者 os.makedirs
https://docs.python.org/2/library/os.html
os.makedirs 创建所有目录,因此如果我在 shell 中输入以下命令(并且没有得到任何输出):
$ ls $ python >>> import os >>> os.listdir(os.getcwd()) [] >>> os.makedirs('alex/is/making/a/path') >>> os.listdir(os.getcwd()) ['alex']
它已经创建了所有的目录和子目录。os.mkdir 会抛出错误,因为不存在 "alex/is/making/a" 目录。