我有以下代码来创建特定条件的目录。
def create_analysis_folder(self, analysis_id, has_headers):
path = None
if not os.path.exists(analysis_id):
os.makedirs(analysis_id)
os.chdir(analysis_id)
if has_headers == False:
path = os.getcwd() + '/html'
return path
else:
os.makedirs('html')
os.chdir('html')
shutil.copy("../../RequestURL.js", os.getcwd())
return os.getcwd()
执行时,这给了我一行错误
os.makedirs(analysis_id)
错误说OSError: [Errno 2] No such file or directory: '39'
。但是我在处理器中创建一个目录然后为什么我会收到这样的错误。
答案 0 :(得分:2)
问题是您chdir
,正如我在评论中已经说过的那样。这里发生了什么:
>>> os.makedirs('a/b/c') # create some directories
>>> os.chdir('a/b/c') # change into this directory
>>> os.rmdir('../c') # remove the current directory
>>> os.makedirs('z') # trying to create a directory in a non-existing directory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 2] No such file or directory: 'z'
处理此类问题的正确方法是:
BASE_DIR = os.getcwd() # or any other path you want to work with
def create_analysis_folder(self, analysis_id, has_headers):
if not os.path.exists(os.path.join(BASE_DIR, analysis_id)):
os.makedirs(os.path.join(BASE_DIR,analysis_id))
path = os.path.join(BASE_DIR, analysis_id, 'html')
if has_headers:
os.makedirs(path)
shutil.copy(os.path.join(BASE_DIR, "RequestURL.js"), path)
return path