首页 > 解决方案 > 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: enter image description here

标签: pythonpython-os

解决方案


而不是 '+' 更好地使用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()

推荐阅读