Home > Mobile >  How to get absolute file path of folder from user input in python? The input gets added at the end o
How to get absolute file path of folder from user input in python? The input gets added at the end o

Time:11-21

import os

print("enter folder name")
FolderName = input()

flag = os.path.isabs(FolderName)

if flag == False:
    path = os.path.abspath(FolderName)
    print("The absolute path is: " ,path)

What am I doing wrong here? Let's say the Folder name input is Neon.

The code output gives C:\Users\Desktop\Codes\Neon\Neon

Instead what I want is: C:\Users\Desktop\Codes\Neon\

CodePudding user response:

The os.path.abspath function normalizes the users current working directory and the input argument and then merges them together.

So if your input is 'Neon' and your current working directory is C:\Users\Desktop\Codes\Neon, then the output is C:\Users\Desktop\Neon\Neon.

Likewise if your input is fkdjfkjdsk then the output would be C:\Users\Desktop\Neon\fkdjfkjdsk.

If you are looking for a way to get the absolute path of the current directory you can use:

os.getcwd()

For the official definition:

os.path.abspath(path)

Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

CodePudding user response:

You are probably running your code when you are at the C:\Users\Desktop\Codes\Neon\ directory

Therefore, when you run os.path.abspath("Neon"), the function is assuming you are trying to refer to a file in the current directory, and returns C:\Users\Desktop\Codes\Neon\Neon.

If you want to have the absolute path of the current directory, use:

os.path.abspath(".")

CodePudding user response:

Most of the function inside the path module of the os library doesn't perform file/directory presence checks before performing operations. i.e., It is probable that if you enter the path to a filesystem object that doesn't exist, the function would still return a result for it.

Your current working directory of the Python file is not the one you expect.

Previous answers have covered the liability of the abspath function. The following code would produce the desired output (only for your case).

import os

os.chdir(r"C:\Users\Desktop\Codes")

print("enter folder name")
FolderName = input()

flag = os.path.isabs(FolderName)

if flag == False:
    path = os.path.abspath(FolderName)
    print("The absolute path is: " ,path)

But if you want to be sure, first display the current working directory to assure that the parent directory is the correct one. Also, include some directory presence functions within the code (such as isdir) in the code to assure that the directory name provided as input is real.

  • Related