
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I list the contents of a directory in Python?
os.listdir(my_path) will get you everything that's in the my_path directory - files and directories.
Example
You can use it as follows:
>>> import os >>> os.listdir('.') ['DLLs', 'Doc', 'etc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'share', 'tcl', 'Tools', 'w9xpopen.exe']
If you want just files, you can filter it using isfile:
>>> import os >>> file_list = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f))] >>> print file_list ['LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'w9xpopen.exe']
- Related Questions & Answers
- How do I list all files of a directory in Python?
- How can I get the list of files in a directory using C/C++?
- How can I get the list of files in a directory using C or C++?
- How to Copy the entire contents of a directory in C#?
- How can I get the current contents of an element in webdriver?
- How can I iterate over files in a given directory in Python?
- How can I create a python directory if it does not exist?
- Java program to merge contents of all the files in a directory
- How can I get a list of locally installed Python modules?
- How do I get the parent directory in Python?
- How can I create a directory if it does not exist using Python?
- How can I remove the same element in the list by Python
- How do I create a Java string from the contents of a file?
- How do I find the location of my Python site-packages directory?
- Dictionary creation using list contents in Python
Advertisements