所以我希望它独立于使用代码的计算机,所以我希望能够在当前目录中创建一个目录并将我的绘图保存到该新文件中.我看了一些其他的问题并试了一下(我有两次尝试,一次注释掉):
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
Run Code Online (Sandbox Code Playgroud)
我收到错误:
AttributeError: 'module' object has no attribute 'mkdirs'
Run Code Online (Sandbox Code Playgroud)
我也想知道我在目录中保存它的想法是否有效,我无法测试,因为我在上面的部分中遇到了错误.
您正在寻找:
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']
Run Code Online (Sandbox Code Playgroud)
它已经制作了所有目录和子目录。os.mkdir 会给我一个错误,因为没有“alex/is/making/a”目录。