Python os模块之文件操作

时间:2023-03-09 00:17:33
Python os模块之文件操作

基本概念:C:\\haoguo.txt

路径: C:\\

文件名: haoguo

后缀名:.txt

1. 文件名与后缀分离

Python os模块之文件操作

2. 路径与文件分离

Python os模块之文件操作

3. 获取当前路径

Python os模块之文件操作

4. 文件名与后缀合并

Python os模块之文件操作

5. 路径与文件合并

Python os模块之文件操作

6. 穷举path下所有文件

Python os模块之文件操作

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. 集合交:提取两个集合共有的元素

Python os模块之文件操作

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)

 总结:文件名、后缀名、路径名的分拆和合并与集合的交、并操作组合在一起,可以完成看似复杂的文件操作