Есть ли простой способ получить путь к подпапке? - PullRequest
0 голосов
/ 29 марта 2020

Таким образом, моя программа дает пользователю право создавать папки и подпапки ... До сих пор мне удавалось создать папку в каталоге по умолчанию, но мне сложно, когда я пытаюсь создать подпапку. ..Я пытаюсь решить часами, но не могу. Если кто-то может мне помочь, это будет очень круто !!! Это комментарии к коду для лучшего понимания. Спасибо

import os
from os import listdir
from pathlib import Path

def display_menu(): #here is the menu for our display
    print("The File Manager program")
    print()
    print("COMMAND MENU")
    print("List - list all folders/subfolders/files")
    print("add - add a folder/subfolder/file")
    print("exit - Exit program")
    print()

def add(fm_list):
    msg = input("What do you want to create?: \n Insert 1 for Folder "
                "\n Insert 2 for Subfolder."
                "\n Insert 3 to choose a different location than DEFULT ")
    if msg == "1":
        folder = input("Name of the folder: ")
        fm_list.append(folder)
        os.chdir('F:\\Test')  # this path is our test path where folders and subfolders and files will be stored
        os.mkdir(folder)
        choice = input("Do you want to add a subfolder to this folder?: (y/n): ")
        if choice == "y":
            #In below, I have difficulties to make a path for the subfolder
            #I have tried all I know but nothing...
            #Instead of making the subfolder in the appropriate folder
            #it creates a folder
            subfolder = input("Name of the subfolder: ")
            fm_list.append(subfolder)
            os.chdir('F:\\Test\\')#HERE
            os.mkdir(subfolder)
            print(folder + " was added to the list of folder.")
            print(subfolder + " was added to " + folder)
        else:
            os.chdir('F:\\Test')  # this path is our test path where folders and subfolders and files will be stored
            #os.mkdir(folder)
            #os.chdir(folder)
            print(folder + " was added to the list of folder.")
            print("Your folder path is : " + str(Path.cwd()))  
def main():
    listdir(my_path)
    fm_list =[]
    display_menu()
    while True:
        command = input("Command: ")
        if command.lower() == "list":
            list(fm_list)
        elif command.lower() == "add":
            add(fm_list)
        elif command.lower() == "copy":
            copy(fm_list)
        elif command.lower() == "exit":
            break
        else:
            print("Not a valid command.\n")


if __name__ == '__main__':
    main()

1 Ответ

0 голосов
/ 29 марта 2020

После прочтения предоставленного вами кода я заметил, что вы создаете папку и подпапку на одном уровне.

Чтобы создать папку, предполагая, что ваша песочница «F: \ Test», вы пишете this:

 os.chdir('F:\\Test') # you changed your current directory to 'F:\\Test' (chdir means change directory equivalent to cd in linux shell)
 os.mkdir(folder) # you created a folder

 ... # after a few lines

 os.chdir('F:\\Test') # you're still in the same directory
 os.mkdir(subfolder) # folder and subfolder are thus created under the same directory

Поскольку вы не изменили свой текущий каталог до создания подпапки, вы получите две папки на одном уровне. Вот мое предложение.

Подпапка должна находиться внутри папки, ранее созданной в «F: \ Test».

 os.chdir('F:\\Test') #changed the current directory to 'F:\Test'
 folder = 'Folder' # the name of the folder
 os.mkdir(folder)  # creates a folder inside 'F:\Test' and you get 'F:\Test\Folder'

 subfolder = 'Subfolder'

 # You need to concatenate 'F:\\Test' with the parent folder of your subfolder. I assume that you picked the previously created folder.

 os.chdir('F:\\Test\\' + folder) # changed the current directory to 'F:\Test\Folder'
 os.mkdir(subfolder) # creates a folder inside 'F:\Test\Folder' and you get 'F:\Test\Folder\Subfolder'
...