Bricktop
Bricktop

Reputation: 153

How to output extension only from splitExt?

I have this old batch code for taking files (that are not in use) in a directory root, and putting them in directories (using filename for dir name):

for %%s in (*.*) do if not "%%~xs"==".!qB" if not "%%~xs"==".parts" (
    md "%%~ns" & move "%%s" "%%~ns\"
    if exist "%%s" rd "%%~ns"
)

this would take a d:\currentdir\filename.ext file and use filename to nest it into d:\currentdir\filename\filename.ext, unless the file extension is a known temp file like .!qB or .parts.

I am trying to rewrite this into python..

rootfiles = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in rootfiles:
    print(os.path.splitext(f))

I'm stuck at splitExt, how do I get only the extension variable so I can exclude the known temp extensions mentioned? I don't get it from the documentation.

Upvotes: 1

Views: 184

Answers (2)

Aaron Bentley
Aaron Bentley

Reputation: 1380

os.path.splitext returns a tuple. You can select either value using the standard brackets like you would with a list.

rootfiles = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in rootfiles:
    print(os.path.splitext(f)[1])

Upvotes: 1

kantal
kantal

Reputation: 2407

Try it:

rootfiles = [f for f in os.listdir('.') if os.path.isfile(f) and not f.endswith(".!qB") and not f.endswith(".parts")]

Upvotes: 2

Related Questions