0

I am running the following code :

foldarz = [ f.path for f in os.scandir('.') if f.is_dir() ] print(foldarz) 

This prints the folder name correctly, but with a prepended ".\". I don't want the ".\".

I know I can split the string etc, but I assume there's a better way without having to call another function.

3
  • 1
    I guess you can do: os.path.basename(f) instead of f.path. Commented Feb 5, 2020 at 17:36
  • f.path[2:] or f.path[3:]? Or f.name? ... docs.python.org/3/library/os.html#os.DirEntry.name Commented Feb 5, 2020 at 17:39
  • 1
    f.name works for me, maybe I misread the problem. Commented Feb 5, 2020 at 17:54

3 Answers 3

2

You can do os.path.basename:

foldarz = [os.path.basename(f) for f in os.scandir('.') if f.is_dir()] 
Sign up to request clarification or add additional context in comments.

4 Comments

Looks like you're calling another function — something the OP wishes to avoid.
That seems to be the question (although that's not clear based on a comment made by OP).
I just noticed. How I read the question is like OP doesn't want to use string functions like split.
For the record, I personally think your answer's fine (because I don't know why calling a function is an issue).
1

os.path.normpath should help you remove the leading '.\' and give you the normalized path preferred by your operating system (think '/' instead of '\' depending upon user's OS)

foldarz = [os.path.normpath(f) for f in os.scandir('.') if f.is_dir()] 

Comments

0

If you don't want to use other functions, you can also use os.DirEntry.name:

foldarz = [ f.name for f in os.scandir('.') if f.is_dir() ] print(foldarz) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.