Summary related to python file operations that I often use but check every time
Get a list of files in the specified folder as a list
import glob
folder = "./tmp/"
img_path_list = glob.glob(folder)
You can also get a list of specific files by using wildcards The following gets only png files as a list
img_path_list = glob.glob(folder + "*.png ")
Get the file name as a character string from the specified path
import os
filepath = './tmp/hogehoge.ext'
filename = os.path.basename(filepath)
print(filename) # hogehoge.ext
When acquiring without extension
filename_only = os.path.splitext(os.path.basename(filepath))[0]
print(filename_only) # hogehoge
Check if the save destination folder exists when saving the file, etc. If it does not exist, create a new one
import os
filepath = "./hogehoge2/"
if not os.path.exists(filepath):
os.makedirs(filepath)
Recommended Posts