基本概念:C:\\haoguo.txt
路徑: C:\\
文件名: haoguo
后綴名:.txt
1. 文件名與后綴分離
2. 路徑與文件分離
3. 獲取當前路徑
4. 文件名與后綴合並
5. 路徑與文件合並
6. 窮舉path下所有文件
7. 獲取path下后綴名為postfix的所有文件列表
def get_imlist(path, postfix): """ Return a list of filenames for all postfix images in a directory Parameters: ----------- path: strings directory containing the images postfix: strings image format, i.e. .jpg Return: ------- a list of file names """ return [os.path.join(path, f) for f in os.listdir(path) if f.endswith(postfix)]
8. 將srcPath下的一個文件haoguo.txt復制到destDir
import shutil shutil.copy(os.path.join(srcPath,'haoguo.txt'), destDir)
9. 集合交:提取兩個集合共有的元素
10. 提取srcPath中文件名和srcPath_ref中文件名相同的文件到destDir
imglist_ref = os.listdir(srcPath_ref) for idx in range(0, len(imglist_ref)): (shotname, extension) = os.path.splitext(imglist_ref[idx]) imglist_ref[idx] = shotname imglist = os.listdir(srcPath) for idx in range(0, len(imglist)): (shotname, extension) = os.path.splitext(imglist[idx]) imglist[idx] = shotname ret = list(set(imglist).intersection(set(imglist_ref))) for idx in ret: shutil.copy(os.path.join(srcPath,idx+'.jpg'), destDir)
總結:文件名、后綴名、路徑名的分拆和合並與集合的交、並操作組合在一起,可以完成看似復雜的文件操作