-1
I have the following piece of code to make a directory on particular conditions.
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()
Upon execution this gives me an error in line
os.makedirs(analysis_id)
The error says OSError: [Errno 2] No such file or directory: '39'. But I am in the processor creating a directory then why am I getting an error like this.
python
|
this question
edited Dec 29 '14 at 10:14
J.F. Sebastian 205k 51 408 624 asked Dec 29 '14 at 9:20
station 1,552 9 28 54 It seems your 'analysis_id' is number. Try converting it in string –
Ajay Tanpure Dec 29 '14 at 9:24 1 What is the traceback? Don't use
chdir, after executing
create_analysis_folder you never know, in which directory you are actually. –
Daniel Dec 29 '14 at 9:47
|
1 Answers
1
---Accepted---Accepted---Accepted---
The problem is your chdir as I already stated in my comment. Here's what happens:d this error and what to do answer 1 >>---Accepted---Accepted---Accepted--- Have you noticed that you don't get the error if you run python ./script.py instead of python script.py This is because sys.argv[0] will read ./script.py in the former case, which gives os
>>> 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 "", line 1, in
File "/.../python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 2] No such file or directory: 'z'
The correct way, to handle such a problem is:
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
|
this answer answered Dec 29 '14 at 11:35
Daniel 25.1k 4 19 48
|
ule attempts to open a second program and cashes #!/usr/bin/pythonfrom sys import argv, exitfrom subprocess import Popen, PIPEfrom collections import defaultdictfrom os import path, removedef main():if len(argv) != 4 or not argv[2] i