2015-06-23 24 views
0

我想製作一個腳本,使目錄(名稱輸入) ,並在剛剛創建的輸入文件夾中創建第二個目錄。Python創建用戶輸入的子目錄

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) 

我得到

if not os.path.exists(user_input/user_input1): 
TypeError: unsupported operand type(s) for /: 'str' and 'str' 

我在做什麼錯在這裏?

我試着這樣做:

if not os.path.exists('/user_input1/user_input'): 

但是,這導致它使兩個單獨的目錄沒有子目錄

+0

你做平均'os.path.join(USER_INPUT,user_input1)'。你寫的是用'user_input1'分割(字符串)'user_input'。 – dhke

回答

1

要創建一個子目錄,你需要連接的分離器,兩個輸入端之間,其能做到爲:

if not os.path.exists(os.path.join(user_input, user_input1)): 
    os.makedirs(os.path.join(user_input, user_input1)) 

你需要記住,在檢查這是一個子目錄的第二個輸入字符串,你通過os.path.join(user_input, user_input1),因爲只傳遞user_input1不會創建子目錄。

+0

感謝它的工作! – theButcher

0

os.path.exists()期待一個字符串。使用這個來代替:

if not os.path.exists(os.path.join(user_input, user_input1): 
    os.makedirs(path) 

而且使你的代碼更容易閱讀你不應該重用path變量這樣。它讓讀者對你的代碼感到困惑。這是更清楚:

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) 
0

這應該工作:

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))