python - Making new directory with python os
问题描述
I'm python beginner. I wanted to make 50 directories in my laptop with python. IDK what to do plz help
import os
from os.path import *
home = expanduser('~')
dl_path = home + '\\Downloads'
def main():
if not os.path.exist(dl_path):
print("path does'nt exist")
os.makedirs(dl_path)
if __name__ == '__main__':
a = 1
while a<= 50:
main()
a += 1
This is my code which doesn't work :( I don't know if it's given an error but here it is:
解决方案
而不是 '+' 更好地使用os.path.join
- 它以更智能的方式与文件名一起使用。else
此外,当您执行实际工作而不是引发异常时,您忘记了详细说明该语句。此外,每个新目录都需要一个新名称——它们不能都具有相同的名称。另外,您想要嵌套目录还是同一级别的目录?
这使目录处于同一级别。
import os
from os.path import *
home = expanduser('~')
dl_path = os.path.join(home, 'Downloads')
def main():
if not os.path.exist(dl_path):
print("path does'nt exist")
else:
a = 1
while a <= 50:
os.makedirs(os.path.join(dl_path, str(a)))
a += 1
if __name__ == '__main__':
main()
这使得嵌套目录:
import os
from os.path import *
home = expanduser('~')
dl_path = home
def main():
if not os.path.exist(dl_path):
print("path does'nt exist")
else:
a = 1
while a <= 50:
dl_path = os.makedirs(os.path.join(dl_path, 'Downloads'))
a += 1
os.makedirs(dl_path)
if __name__ == '__main__':
main()
推荐阅读
- java - 解密 AES-GCM 时遇到问题
- php - Woocommerce 自定义端点内容网址
- python - 在熊猫中生成给定范围内的随机日期
- laravel - 我无法更新 laravel 5 中的字段
- c++ - `decltype((const int)a)` 和 `decltype((const int)1)` 的不同类型
- bash - 与单词边界不工作的bash中的多行字符串匹配
- ibm-cloud - 如何在 watson 对话中将动态输入与实体映射 (Bluemix)
- java - 代码在 Android Studio 中的某个时间会被还原几个小时或一整天
- python - 如何在 OpenCV 中将视频写入内存
- c - C中的通用数组元素交换