Reputation: 75
I am trying to make a script that makes a directory (name input) and makes a second directory in that just created input folder.
import os
import sys
user_input = raw_input("Enter name: ")
user_input1 = raw_input('Enter case: ')
path = user_input
if not os.path.exists(path):
os.makedirs(path)
path = user_input1
if not os.path.exists(user_input/user_input1):
os.makedirs(path)
I get
if not os.path.exists(user_input/user_input1):
TypeError: unsupported operand type(s) for /: 'str' and 'str'
What am I doing wrong here?
I tried doing this:
if not os.path.exists('/user_input1/user_input'):
But that results in it making two separate directories not subdirectories
Upvotes: 2
Views: 11817
Reputation: 11039
os.path.exists()
is expecting a string. Use this instead:
if not os.path.exists(os.path.join(user_input, user_input1):
os.makedirs(path)
Also to make your code easier to read you shouldn't reuse the path
variable like that. It make sit confusing to others reading your code. This is much clearer:
import os
import sys
path1 = raw_input("Enter name: ")
path2 = raw_input('Enter case: ')
if not os.path.exists(path1):
os.makedirs(path1)
if not os.path.exists(os.path.join(path1, path2):
os.makedirs(path2)
Upvotes: 0
Reputation: 22954
To create a sub directory, you need to concatenate the separator in between the two inputs which can be done as :
if not os.path.exists(os.path.join(user_input, user_input1)):
os.makedirs(os.path.join(user_input, user_input1))
You need to keep in mind that while checking for the second input string which is a sub directory, you pass os.path.join(user_input, user_input1)
, as passing only user_input1
would not create a sub directory.
Upvotes: 3
Reputation: 187
this should work:
import os
import sys
user_input = raw_input("Enter name: ")
user_input1 = raw_input('Enter case: ')
path1 = user_input
if not os.path.exists(path1):
os.makedirs(path1)
path2 = user_input1
if not os.path.exists(os.path.join(user_input, user_input1)):
os.makedirs(os.path.join(path1, path2))
Upvotes: 0