I am using the following code to create a list of image files with tif extension. The current result of the code is a list with the address of the .tif files.
raster_list=[] def getFiles(path): for file in os.listdir(path): if file.endswith(".tif"): raster_list.append(os.path.join(path, file)) getFiles(fpath) print(raster_list) len(raster_list)
result:
['C:/dataset/test\ras1.tif', 'C:dataset/test\ras2.tif', 'C:/dataset/test\ras3.tif', 'C:/dataset/test\ras4.tif', 'C:/dataset/test\ras5.tif']
How can I revise the code to create two lists a) name of the file with .tif b) name of the file. here is the example:
raster_list = ['ras1.tif','ras2.tif','ras3.tif','ras4.tif', 'ras5.tif' ] raster_name = ['ras1','ras2','ras3','ras4', 'ras5']
edit to the code from solutions:
from os import path raster_list=[] def getFiles(path): for file in os.listdir(path): if file.endswith(".tif"): raster_list.append(file) #remove the os.join, just take the file name getFiles(fpath) raster_names = [path.splitext(x)[0] for x in raster_list] print(raster_list) print(raster_names)
result:
['ras1.tif', 'ras2.tif', 'ras3.tif', 'ras4.tif', 'ras5.tif'] ['ras1', 'ras2', 'ras3', 'ras4', 'ras5']
Advertisement
Answer
For the first list you want you can just use the function split(“”) on each one of the term of your list and use the last element of the list created by split. And for the second one you can just take the first list you’ve created and split on “.”, you will just have to save the first element of the list.
L = ['C:/dataset/test\ras1.tif', 'C:dataset/test\ras2.tif', 'C:/dataset/test\ras3.tif', 'C:/dataset/test\ras4.tif', 'C:/dataset/test\ras5.tif'] raster_list = [] raster_name = [] for i in L: a = i.split("\")[1] raster_list.append(a) raster_name.append(a.split(".")[0]) print(raster_list, raster_name)
But you can also try to not include the path in rather_list like that:
raster_list=[] def getFiles(path): for file in os.listdir(path): if file.endswith(".tif"): raster_list.append(file) #remove the os.join, just take the file name getFiles(fpath) print(raster_list) len(raster_list)
You can merge the two to have this:
raster_list=[] raster_names=[] def getFiles(path): for file in os.listdir(path): if file.endswith(".tif"): raster_list.append(file) raster_names.append(file.split(".")[0]) getFiles(fpath) print(raster_list, raster_names)