1

我正在尝试制作一个创建目录(名称输入)并在刚刚创建的输入文件夹中创建第二个目录的脚本。

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

但这导致它创建了两个单独的目录而不是子目录

4

3 回答 3

2

要创建子目录,您需要在两个输入之间连接分隔符,可以这样做:

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不会创建子目录。

于 2015-06-23T14:34:06.220 回答
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)
于 2015-06-23T14:34:41.360 回答
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))
于 2015-06-23T14:37:32.300 回答