What is the best way to look inside a folder with python if you want a filename and directory name but don't need a path ...
For example, if the following files exist in the test directory
test.csv
test.py
test.sh
test.txt
test1
test2
test3
If you use the glob
module, it will look like this.
>>> import glob
>>> glob.glob('test/*')
['test/test.csv', 'test/test.py', 'test/test.sh', 'test/test.txt', 'test/test1', 'test/test2', 'test/test3']
However, ideally
>>> import hoge
>>> hoge.hoge('test/*')
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']
I want it to look like this.
There are the following methods, but it is painful that you cannot specify a wildcard.
>>> import os
>>> os.listdir('test/')
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']
Based on the above, I came up with the following three
The most commonly used method is to use commands
.
>>> import commands
>>> commands.getoutput('ls test/* | xargs -n 1 basename').split("\n")
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']
Besides, is it a straightforward approach to get only the basename of the path obtained by the glob
module?
>>> import glob
>>> [r.split('/')[-1] for r in glob.glob('test/*')]
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']
>>> import glob, os
>>> [os.path.basename(r) for r in glob.glob('test/*')]
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']
I was curious about how everyone was doing it, so I wrote my own method for the time being. Please teach me if there is any good way.
Recommended Posts