不聞不若聞之,聞之不若見之,見之不若知之,知之不若行之。——荀子《儒效篇》
常用的解析檔案方法
os.path.splitext:分離檔案名與擴充名
def _parse_filename(filename): # 解析檔案名
"""Parse meta-information from given filename.
Parameters
----------
filename : str
A VeRi image filename.
Returns
-------
(int, int, str, str) | NoneType
Returns a tuple with the following entries:
* Unique ID of the individual in the image
* Index of the camera which has observed the individual
* Filename without extension
* File extension
Returns None if the given filename is not a valid filename.
"""
filename_base, ext = os.path.splitext(filename) # 分離檔案名與擴充名
if '.' in filename_base:
# Some images have double filename extensions.
filename_base, ext = os.path.splitext(filename_base)
if ext != ".jpg":
return None
vehicle_id, cam_num, frame_idx, detection_idx = filename_base.split('_')
return int(vehicle_id), int(cam_num[1]), filename_base, ext
os.path.join:路徑拼接
os.path.join()函數:連接配接兩個或更多的路徑名元件,參數可以傳入多個路徑
1.如果各元件名首字母不包含’/’,則函數會自動加上
2.如果有一個元件是一個絕對路徑,則在它之前的所有元件均會被舍棄
3.如果最後一個元件為空,則生成的路徑以一個’/’分隔符結尾
import os
print("1:",os.path.join('aaaa','/bbbb','ccccc.txt'))
print("2:",os.path.join('/aaaa','/bbbb','/ccccc.txt'))
print("3:",os.path.join('aaaa','./bbb','ccccc.txt'))
output
1: /bbbb\ccccc.txt
2: /ccccc.txt
3: aaaa\./bbb\ccccc.txt