简体   繁体   English

Python使用用户输入创建子目录

[英]Python creating subdirectory with user input

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 但这导致它使两个单独的目录而不是子目录

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. 您需要记住,在检查第二个输入字符串(即子目录)时,请传递os.path.join(user_input, user_input1) ,因为仅传递user_input1不会创建子目录。

os.path.exists() is expecting a string. os.path.exists()需要一个字符串。 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. 同样,为了使代码更易于阅读,您不应重复使用path变量。 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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM