os.listdir()
will get you everything that’s in a directory – files and directories.
If you want just files, you could either filter this down using os.path
:
from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
or you could use os.walk()
which will yield two lists for each directory it visits – splitting into files and dirs for you. If you only want the top directory you can break the first time it yields
from os import walk f = [] for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break
or, shorter:
from os import walk filenames = next(walk(mypath), (None, None, []))[2] # [] if no file
Related Posts:
- Find the current directory and file’s directory [duplicate]
- How to find if directory exists in Python
- Importing modules from parent folder
- Importing modules from parent folder
- How do I list all files of a directory?
- How do I get the full path of the current file’s directory?
- Creating files and directories via Python
- Extract a part of the filepath (a directory) in Python
- How can I find script’s directory?
- Python copy files to a new directory and rename if file name already exists
- How do I create a constant in Python?
- JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- Pandas DataFrame Groupby two columns and get counts
- What is __init__.py for?
- How to fix ‘Object arrays cannot be loaded when allow_pickle=False’ for imdb.load_data() function?
- TypeError: ‘float’ object is not subscriptable
- How to show all columns’ names on a large pandas dataframe?
- ImportError: No module named matplotlib.pyplot
- How to remove EOFError: EOF when reading a line?
- How do I define a function with optional arguments?
- How to use Python to execute a cURL command?
- Reading from RS 232 port using python
- Ran Pycharm debug which ended with exit code -1
- How to deal with SettingWithCopyWarning in Pandas
- Python return statement error ” ‘return’ outside function”
- Why do people write #!/usr/bin/env python on the first line of a Python script?
- How do I parallelize a simple Python loop?
- What does the power operator (**) in python translate into?
- How can I remove a trailing newline?
- ImportError: cannot import name main when running pip –version command in windows7 32 bit
- pygame.error: video system not initialized
- How to draw a circle in PyGame?
- TypeError: ‘numpy.float64’ object is not callable?
- Why do I get: “Length of values does not match length of index” error?
- How to remove all the punctuation in a string? (Python)
- Cross Entropy in PyTorch
- How to import the class within the same directory or sub directory?
- why should I make a copy of a data frame in pandas
- How to create a new text file using Python
- How to normalize a NumPy array to a unit vector?
- What does & mean in python
- how do you check your django version in cmd
- ‘numpy.float64’ object is not iterable
- Python: ‘break’ outside loop
- Python 3: ImportError “No Module named Setuptools”
- Return JSON response from Flask view
- Convert hex to binary
- TypeError: ‘encoding’ is an invalid keyword argument for this function
- How to calculate a logistic sigmoid function in Python?
- Why is python setup.py saying invalid command ‘bdist_wheel’ on Travis CI?
- How to write bytes to file?
- PyLint “Unable to import” error – how to set PYTHONPATH?
- ImportError: No module named scipy
- What is the Python 3 equivalent of “python -m SimpleHTTPServer”
- What does -> mean in Python function definitions?
- Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules
- Count unique values using pandas groupby
- Running Bash commands in Python
- (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape
- How do you split a list into evenly sized chunks?
- Ignoring NaNs with str.containsv
- How to split a string into a list of characters in Python?
- Find where python is installed (if it isn’t default dir)
- log2 in python math module
- python ZeroDivisionError: float division by zero – how to treat it as an exception
- Python map object is not subscriptable
- Why does pycharm propose to change method to static
- append new row to old csv file python
- Distributed 1.21.8 requires msgpack, which is not installed
- Python Library Path
- .pyw files in python program
- Get the cartesian product of a series of lists?
- No module named googlesamples.assistant.auth_helpers
- Solution for SpecificationError: nested renamer is not supported while agg() along with groupby()
- Why is there no tuple comprehension in Python?
- pip: no module named _internal
- Image.open() cannot identify image file – Python?
- python socket programming OSError: [WinError 10038] an operation was attempted on something that is not a socket
- python math domain errors in math.log function
- Append a dictionary to a dictionary
- Error “‘type’ object has no attribute ‘__getitem__'” when iterating over list[“a”,”b”,”c”]
- Python: “TypeError: __str__ returned non-string” but still prints to output?
- ImportError: No module named ‘django.core.urlresolvers’
- Numpy, multiply array with scalar
- What is the difference between random.randint and randrange?
- How do I access my webcam in Python?
- Boolean Series key will be reindexed to match DataFrame index
- What is the easiest way to clear a database from the CLI with manage.py in Django?
- Printing one character at a time from a string, using the while loop
- Change the name of a key in dictionary
- Check if an object exists
- How do I calculate the date six months from the current date using the datetime Python module?
- How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?
- TypeError: can only concatenate tuple (not “int”) in Python
- Write a program using integers user_num and x as input, and output user_num divided by x three times
- Logical operators for Boolean indexing in Pandas
- Transposing a 1D NumPy array
- Explaining Python’s ‘__enter__’ and ‘__exit__’
- numpy.float64 object is not iterable…but I’m NOT trying to
- Converting a list to a set changes element order