Is there a way to list the files (not directories) in a directory with Python? I know I could use os.listdir
and a loop of os.path.isfile()
s, but if there's something simpler (like a function os.path.listfilesindir
or something), it would probably be better.
/W - Displays only filenames and directory names (without the added information about each file) in a five-wide display format. dir c:*. This form of the DIR command will also display directories. They can be identified by the DIR label that follows the directory name.
You can use the DIR command by itself (just type “dir” at the Command Prompt) to list the files and folders in the current directory.
This is a simple generator expression:
files = (file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file))) for file in files: # You could shorten this to one line, but it runs on a bit. ...
Or you could make a generator function if it suited you better:
def files(path): for file in os.listdir(path): if os.path.isfile(os.path.join(path, file)): yield file
Then simply:
for file in files(path): ...
files = next(os.walk('..'))[2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With