To list the files in a directory, you can uselistdir()
Provided methodos
Built-in modules:
import os
dirname = ‘/users/Flavio/dev’
files = os.listdir(dirname)
print(files)
To get the full path of the file, you can useos.path.join()
method:
import os
dirname = ‘/users/Flavio/dev’
files = os.listdir(dirname)
temp = map(lambda name: os.path.join(dirname, name), files)
print(list(temp))
To list only files or only directories, you can useos.path.isfile()
withos.path.isdir()
:
import os
dirname = ‘/users/Flavio/dev’
dirfiles = os.listdir(dirname)
fullpaths = map(lambda name: os.path.join(dirname, name), dirfiles)
dirs = []
files = []
for file in fullpaths:
if os.path.isdir(file): dirs.append(file)
if os.path.isfile(file): files.append(file)
print(list(dirs))
print(list(files))
More python tutorials:
- Introduction to Python
- 在macOS上安装Python 3
- Run Python program
- Python 2 and Python 3
- Basics of using Python
- Python data types
- Python operators
- Python string
- Python boolean
- Python numbers
- Python, accepts input
- Python control statements
- Python list
- Python tuple
- Python set
- Python dictionary
- Python functions
- Python objects
- Python loop
- Python module
- Python class
- Python standard library
- Debug Python
- Python variable scope
- Python, accept parameters from the command line
- Python recursion
- Python nested functions
- Python Lambda function
- Python closure
- Python virtual environment
- Use Python to use GoPro as a remote webcam
- Python, how to create a list from a string
- Python decorator
- Python Docstrings
- Python introspection
- Python notes
- Python, how to list files and folders in a directory
- Python, how to check if a number is odd or even
- Python, how to get detailed information of a file
- Python, how to check if a file or directory exists
- Python exception
- Python, how to create a directory
- Python, how to create an empty file
- Python, `with` statement
- Python, create a network request
- Python, use `pip` to install third-party software packages
- Python, read file content