A quick way to read a file name from a directory?

Given the structure of the local directory /foo/barand assuming that the path contains exactly one file (the file name and contents do not matter), what is a fast enough way to get the file name of this single file (NOT file contents)?

+5
source share
3 answers

1st element os.listdir()

import os
os.listdir('/foo/bar')[0]
+13
source

Well, I know this code works ...

for file in os.listdir('.'):
    #do something
+2
source

you can also use glob

import glob
print glob.glob("/path/*")[0]
+1
source

All Articles