Reducing a zero from the begining of a string for reading the name of folders

Viewed 41

For Processing many videos, the main code reads the folders of videos. To be clearer, each video has a specific folder and inside it, its frames are existed. The code for reading the folder names of each video is designed to read in this style (e.g. 0001, 0001, ...) but the name of the folders are in this style (e.g. 001, 002, ...). So, how it is possible to modify the code to be compatible with the name of the folders. The main error raises in the following function where the name of the folders are read. how it is possible to modify this function to read the folders in the style of (001)

class Dataset3D(Dataset):
    def __init__(self, path_data, len_snippet, size=(224,384), target = False, list_videoName=[]):
         self.path_data = path_data 
         self.len_snippet = len_snippet 
         self.size=(size[1], size[0])
         self.target = target
         self.list_video_frames=[] #it contains one element for each video; each element is a list of frame names of that video
         self.list_video_annt=[] #it contains one element for each video; each element is a list of annt names of that video
         self.list_num_frame=[] #it contains one element for each video; each element is the number of frames of that video
         
         print("Init Dataset...")
         if len(list_videoName)>0:
             self.list_video_name=list_videoName
             self.list_video_name=[v for v in self.list_video_name]
             self.list_video_name.sort()
         elif path_data==os.path.join('data', 'LEDOV'):
             self.list_video_name=pd.read_csv(os.path.join(path_data,'train.csv'))['0'].values.tolist()
             self.list_video_name=[os.path.splitext(v)[0] for v in self.list_video_name]
             self.list_video_name.sort()
         else:
             self.list_video_name=[d for d in os.listdir(os.path.join(path_data, 'frames')) if os.path.isdir(os.path.join(path_data, 'frames', d))]
        
        
         for vid in self.list_video_name:
             #list of frame names of a single video
             list_frame_names=[f for f in os.listdir(os.path.join(path_data, 'frames', vid)) if os.path.isfile(os.path.join(path_data, 'frames', vid, f))]
             list_frame_names.sort()

 
1 Answers

If I understand right, the problem is how to convert a numerical string to a diferent number of leading zeros? In that case:

new_string = f"{int(old_string):04d}"

This converts the old string to an integer, then formats that integer as a string. The 04 part means "make the string at least 4 characters long, by padding with zeros". If you want a different size change the 4 to something else.

Examples:

old_string = "0000100"
f"{int(old_string):04d}".  # "0100"
f"{int(old_string):06d}".  # "000100"
f"{int(old_string):02d}".  # "100", the size 2 is smaller than the number requires, so the output is longer than 2.
Related