Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to read filename from directory?

Tags:

python

path

Given a local directory structure of /foo/bar, and assuming that a given path contains exactly one file (filename and content does not matter), what is a reasonably fast way to get the filename of that single file (NOT the file content)?

like image 305
nikola Avatar asked Jan 03 '10 10:01

nikola


People also ask

How do I read all files in a directory in Python?

To get a list of all the files and folders in a particular directory in the filesystem, use os. listdir() in legacy versions of Python or os. scandir() in Python 3.


2 Answers

1st element of os.listdir()

import os
os.listdir('/foo/bar')[0]
like image 146
gimel Avatar answered Sep 24 '22 19:09

gimel


Well I know this code works...

for file in os.listdir('.'):
    #do something
like image 22
Ritwik Bose Avatar answered Sep 22 '22 19:09

Ritwik Bose