The __glob module __ is useful for getting a list of files in the same directory.
Try running glob in the directory where the following files are saved. data1.txt, data10.txt, data2.txt, data3.dat, data99.txt, result1.txt, result2.dat
You can get a list of all the files in the same directory by the following process.
import glob
filelist=glob.glob('*')
print(filelist)
Execution result
['data1.txt', 'data10.txt', 'data2.txt', 'data3.dat', 'data99.txt', 'result1.txt', 'result2.dat']
You can use the wildcard'*' to list only filenames that meet certain criteria. In the example below, the files whose file names start with'data'and those whose extension is'.txt' are listed.
filelist=glob.glob('data*') #'data'List all file names that start with
print(filelist)
filelist=glob.glob('*.txt') #'.txt'List all filenames ending in
print(filelist)
Execution result
['data1.txt', 'data10.txt', 'data2.txt', 'data3.dat', 'data99.txt']
['data1.txt', 'data10.txt', 'data2.txt', 'data99.txt', 'result1.txt']
If you want to specify the number of characters in the wildcard part, use'?' Instead of'*'. Connect as many'?' As the number of characters you want to specify. The following example can list files with any two characters between'data' and'.txt'.
filelist=glob.glob('data??.txt') #'data'When'.txt'List all files that contain any two characters between
print(filelist)
Execution result
['data10.txt', 'data99.txt']
You can also use []. In this case, the files enclosed in [] that match any one of the alphanumeric characters in [] are listed.
filelist=glob.glob('data[0-9].txt') #[0-9]List all items that have a number from 0 to 9 in the part of
print(filelist)
Execution result
['data1.txt', 'data2.txt']
Recommended Posts