Python file path related functions

  • os.path.join() Combine paths to generate new paths
# os.path.join(path, *paths)
# join two or more paths
import os
os.path.join(os.getcwd(),'data') #获取当前目录并在其后加'\\data'组合成新的目录
  • glob.glob() returns a list of paths that conform to a certain path name pattern
# 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) returns a list of file names in a folder; len() returns the number of files in the folder
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.
  • Path format distinction
'\model' # = 'C:\model'
'model' # 程序文件当前路径下的model文件夹
'.\model' # = 'model'
  • Move files from the original path to the new path
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

Guess you like

Origin blog.csdn.net/qq_35762060/article/details/108275226