Can’t be hard, but I’m having a mental block.
8 Answers
import os
os.listdir("path") # returns list
1 Comment
os.listdir() = os.listdir('.')One way:
import os
os.listdir("/home/username/www/")
glob.glob("/home/username/www/*")
The glob.glob method above will not list hidden files.
Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir method on Path objects:
from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")
5 Comments
.XYZ files in a Unix file-system context), when used with glob.glob("/home/username/www/.*") ?['c:\\users']glob.glob(r'c:\users\*') (glob it doesn't actually list directories, but expands asterisks and such which accomplishes a similar task).pathlib solution, you can use the glob function and then convert it to a list: list(Path("home/username/www").glob(*)). It is slightly more readable IMO.glob.glob or os.listdir will do it.
2 Comments
import glob ENTER glob.glob(r'c:\users') ENTER only seems to return ['c:\\users']. Why is that? I'd like to use glob.glob because as other users have pointed out, it supposedly returns the contents of a directory while also ignoring hidden files. This is important.glob: glob.glob(r'c:\users\*')The os module handles all that stuff.
os.listdir(path)Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
Availability: Unix, Windows.
Comments
In Python 3.4+, you can use the new pathlib package:
from pathlib import Path
for path in Path('.').iterdir():
print(path)
Path.iterdir() returns an iterator, which can be easily turned into a list:
contents = list(Path('.').iterdir())
Comments
Since Python 3.5, you can use os.scandir.
The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file to know if it's a file or not, and that saves CPU time because stat is already done when scanning dir in Windows:
example to list a directory and print files bigger than max_value bytes:
for dentry in os.scandir("/path/to/dir"):
if dentry.stat().st_size > max_value:
print("{} is biiiig".format(dentry.name))
(read an extensive performance-based answer of mine here)
Comments
Below code will list directories and the files within the dir. The other one is os.walk
def print_directory_contents(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)