Python 在当前目录之外创建文件夹时出现问题

问题描述 投票:0回答:1

因此,我可以在与 main.py 所在的路径相同的路径中创建文件夹。但即使使用 os.chdir 并尝试在该目录中创建文件夹,我也无法做到。它可以读取类似的文件夹是否存在,但 mkdir 的部分不执行任何操作。我没有得到打印等。我确实注意到该文件夹处于“只读”状态,但 main.py 文件夹位于该文件夹的子文件夹中,可以很好地创建一个。当我检查该目录时,它说有可写访问权限。

import os
    default_path = os.getcwd()
    new_path = ""
    print("Current directory:", default_path)
    if(input("Do you want to change the directory? (y/n): ") == "y"):
        new_path = input("You can use relative path or absolute path \nEnter the new directory: ")
        new_path = os.path.abspath(new_path)
        if os.path.exists(new_path):
            os.chdir(new_path)
            print("Directory changed to", os.getcwd())
            print(os.access(os.getcwd(), os.W_OK))
        else:
            print("Directory does not exist.")
    
    day_to_start = input("Number to start with(Ex: type 1 for Day 1): ").strip()
    day_to_end = input("Amount to create: ").strip()
    for i in range(int(day_to_start), int(day_to_end) + 1):
        if os.path.exists(f"Day {i}"):
            print(f"Day {i} already exists.")
        else:
            os.mkdir(f"Day {i}")
            print(f"Day {i} created.")
python-3.x directory create-directory
1个回答
0
投票

抱歉,经过长时间的调试,我发现了我的问题,哈哈。

for i in range(int(day_to_start), int(day_to_end) + 1):

不正确,因此一旦 day_to_start 高于 day_to_end ,循环就不会运行,这就是它不创建文件夹的原因..

我已调整为

for i in range(day_to_start, day_to_start + day_to_end):
© www.soinside.com 2019 - 2024. All rights reserved.