Python中目录操作

注意区分路径,目录,文件

路径:path

目录:dir

文件:file

python中的路径分割符

查看系统的分割符:

import os

os.sep

因此,可以直接用os.sep代替使用斜杆或反斜杆

在Windows系统下的分隔符是:\(反斜杠)

在Linux系统下的分隔符是:/(斜杠)

python中路径的三种写法:

  • “C:/Users/shentao/Desktop/TCGA-AO-A0J8” 非转义

  • “C:\\Users\\shentao\\Desktop\\TCGA-AO-A0J8” 转义的方式

  • r“C:\Users\shentao\Desktop\TCGA-AO-A0J8” 声明字符串不需要转义

注意在windows就只用window的路径表示方法

new_dir = str(os.getcwd()).replace("\\","/")

  • python中os.path常用模块

  • os.path.sep:路径分隔符 linux下就用这个了’/’

  • os.path.curdir:当前目录

  • os.path.pardir:父目录

  • os.path.abspath(path):绝对路径

  • os.path.join(): 常用来链接路径

  • os.path.split(path): 把path分为目录和文件两个部分,(head, tail)以列表返回

  • os.path.dirname(path):返回head

  • os.path.basename(path):返回tail

  • os.path.splitdrive(path):drive

  • os.path.splitext(path):extension, (root, ext)

python脚本的当前路径

sys.argv[0]

import sys

print sys.argv[0]#获得的是当前执行脚本的位置(若在命令行执行的该命令,则为空)

sys.path是Python会去寻找模块的搜索路径列表,sys.path[0]和sys.argv[0]是一回事因为Python会自动把sys.argv[0]加入sys.path

os模块

import os

print os.getcwd()#获得当前工作目录

print os.path.abspath('.')#获得当前工作目录

print os.path.abspath('..')#获得当前工作目录的父目录

printos.path.abspath(os.curdir)#获得当前工作目录

注:argv[0]只是得到的是当前脚本的绝对位置;而os模块中的几种获得路径的方法,得到的是当前的工作目录,如:open('1.txt','r'),则会在当前工作目录查找该文件。即大部分的文件操作都是相对于当前工作路径。

os.getcwd()取的是起始执行目录

sys.path[0]或sys.argv[0]取的是被初始执行的脚本的所在目录

os.path.split(os.path.realpath(__file__))[0]取的是__file__所在文件test_path.py的所在目录

改变当前工作路径

可以用:os.chdir(path)

如os.chdir(E:\Program Files),则大部分的文件操作就会是相对于E:\dir1。fobj = open('Hello.txt'),实际会打开E:\Program Files\Hello.txt文件

目录相关模块

os模块在python参考手册16节

os.path模块在Python参考手册11.2节

shutil模块在python参考手册11.10节

os模块--目录操作
  • os.remove

删除文件

  • os.rmdir

删除目录

  • glob模块的glob()

得到的是文件和目录下的完整的路径

  • os.listdir()

只列出给定目录下的文件和文件夹的名字,但不是完整的路径

  • os.scandir()

  • os.walk()

def scan_files(directory, prefix=None, postfix=None):
    files_list = []
    for root, sub_dirs, files in os.walk(directory):
        for special_file in files:
            if postfix:
                if special_file.endswith(postfix):
                    files_list.append(os.path.join(root, special_file))
            elif prefix:
                if special_file.startswith(prefix):
                    files_list.append(os.path.join(root, special_file))
            else:
                files_list.append(os.path.join(root, special_file))

    return files_list
os.path模块--目录操作
os.path.join('datasets', 'image', 'test.jpg')

os.path.split()的功能等价于os.path.dirname() + os.path.basename()的功能

basename表示基址名

用os.path.exists()方法,判断文件和文件夹是一样

可以进一步用是文件还是目录来判断

pathlib模块--目录操作

类图:

PurePath.parts

A tuple giving access to the path’s various components:

>>> p = PurePath('/usr/bin/python3')

>>> p.parts

('/', 'usr', 'bin', 'python3')

>>> p = PureWindowsPath('c:/Program Files/PSF')

>>> p.parts

('c:\\', 'Program Files', 'PSF')

PurePath.parent

The logical parent of the path

PurePath.name

A string representing the final path component, excluding thedrive and root

PurePath.suffix

The file extension of the final component

PurePath.stem

The final path component, without its suffix

PurePath.as_posix()

Return a string representation of the path with forward slashes (/)

PurePath.as_uri()

Represent the path as a file URI. ValueError is raised if the path isn’t absolute.

>>> p = PurePosixPath('/etc/passwd')

>>> p.as_uri()

'file:///etc/passwd'

>>> p = PureWindowsPath('c:/Windows')

>>> p.as_uri()

'file:///c:/Windows'

PurePath.with_name(name)

Return a new path with the namechanged. If the original path doesn’t have a name, ValueError israised

PurePath.with_suffix(suffix)

Return a new path with the suffixchanged. If the original path doesn’t have a suffix, the new suffix is

appended instead

Path.iterdir()

When the path points to a directory, yield path objects of thedirectory contents

Path.mkdir(mode=0o777, parents=False, exist_ok=False)

Create a new directory at this given path

注意parents参数,可以指定为True,连父目录一起创建

If exist_ok is false (the default), FileExistsErroris raised if the target directory already exists

exist_ok表示存在也没有关系

用pathlib模块中的Path().rglob来递归遍历文件:

from pathlib import Path
 
src = "/home/"
for item in Path(src).rglob('*.py'):
    pass
shutil模块--目录操作

文件目录操作汇总

import os
import shutil

def move_file(src, dst):
    shutil.move(src, dst)

def move_dir(src, dst):
    shutil.move(src, dst)

def copy_file(src, dst):
    shutil.copy(src, dst)

def copy_dir(src, dst):
    shutil.copytree(src, dst)

def delete_file(path):
    os.remove(path)

def delete_dir(dir):
    shutil.rmtree(dir)

def rename_file(src, dst):
    os.rename(src, dst)

def rename_dir(src, dst):
    os.rename(src, dst)

def mkdir_singlelayer(path):
    os.mkdir(path)

def mkdir_multilayer(path):
    os.makedirs(path)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wugou2014

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值