python 文件路径相关的函数

  • os.path.join() 组合路径生成新路径
# os.path.join(path, *paths)
# join two or more paths
import os
os.path.join(os.getcwd(),'data') #获取当前目录并在其后加'\\data'组合成新的目录
  • glob.glob() 返回符合某种路径名模式的路径列表
# glob.glob(pathname, *, recursive=False)
# Return a list of paths matching a pathname pattern.
import glob
data_path = 'data/train'
glob.glob(os.path.join(data_path, 'image/*.png'))

result:

['data/train\\image\\10.png',
 'data/train\\image\\11.png',
 'data/train\\image\\12.png',
 'data/train\\image\\13.png',
 'data/train\\image\\14.png',
 'data/train\\image\\15.png',
 'data/train\\image\\16.png',
 'data/train\\image\\17.png',
 'data/train\\image\\18.png',
 'data/train\\image\\19.png']
  • os.listdir(filepath) 返回某文件夹中的文件名列表;len() 返回文件夹中的文件个数
list_fp = os.listdir(filepath)
# Return a list containing the names of the files in the directory.

len(list_fp) # 返回该文件夹中的文件个数
  • str.replace()
str1 = ''
str1.replace()
# Return a copy with all occurrences of substring old replaced by new.
  • 路径格式区分
'\model' # = 'C:\model'
'model' # 程序文件当前路径下的model文件夹
'.\model' # = 'model'
  • 移动文件从原有路径到新路径
import shutil # shutil 是对 os 中文件操作的补充

shutil.move(original_file_path, new_file_path)
  • os.path.isdir()
os.path.isdir(filepath)
# Return true if the pathname refers to an existing directory.
  • shutil.rmtree()
shutil.rmtree()
# Recursively delete a directory tree
# 即删除多级目录
  • os.mkdir() and os.makedirs()
os.mkdir()
# Create a directory

os.makedirs()
# Recursively create a directory tree

猜你喜欢

转载自blog.csdn.net/qq_35762060/article/details/108275226