如何解决Python无法通过将文件夹名称设置为输入来创建子文件夹
我要在文件夹abc中创建文件夹名称1。这是代码。
id=input("enter user id : ")
path = "/abc/" + str(id)
try:
os.mkdir(path)
except OSError:
print ("Creation of the directory %s failed" % path)
else:
print ("Successfully created the directory %s " % path)
我输入1来创建文件夹名称1,但它显示这样的错误。如何解决?
enter user id : 1
Creation of the directory /abc/1 failed
解决方法
尝试使用:
id = input("enter user id : ")
path = "abc/{}".format(id)
try:
file = open(path)
except Exception:
if not os.path.exists(path):
os.makedirs(path)
,
只需尝试:
if not os.path.isdir(path):
os.mkdir(path)
如果该文件夹不存在,则会创建该文件夹。
,然后尝试创建文件路径,如下所示:
path = os.path.join('os.chdir()','abc','id)
使用os.path.join是更好的做法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。