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.
# Only return the names of the files, not full file directories

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

python 获取当前,上级,上上级路径
Python 数据集的相对路径/选择上级文件夹

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值