python os函数_python os模块主要函数

使用python提供的os模块,对文件和目录进行操作,重命名文件,添加,删除,复制目录以及文件等。

一、文件目录常用函数

在进行文件和目录操作时,一般会用到以下几种操作。

1、获得当前;路径

在python中可以使用os.getcwd()函数获得当前的路径。

os.getcwd()

'''帮助文档:Return a unicode string representing the current working directory.'''

该函数不需要传递参数,它返回当前的目录。需要说明的是,当前目录并不是之脚本所在的目录,而是所运行脚本的目录。

修改当前脚本的目录使用os.chdir()函数

os.chdir()

'''帮助文档:chdir(path)

Change the current working directory to the specified path.

path may always be specified as a string.

On some platforms, path may also be specified as an open file descriptor.

If this functionality is unavailable, using it raises an exception.'''

2、获得目录中的内容

在python中可以使用os.listdir()函数获得指定目录中的内容。

os.listdir(path)

''' 帮助文档:listdir(path=None)

Return a list containing the names of the files in the directory.

path can be specified as either str, bytes, or a path-like object. If path is bytes,

the filenames returned will also be bytes; in all other circumstances

the filenames returned will be str.

If path is None, uses the path='.'.

On some platforms, path may also be specified as an open file descriptor;\

the file descriptor must refer to a directory.

If this functionality is unavailable, using it raises NotImplementedError.

The list is in arbitrary order. It does not include the special

entries '.' and '..' even if they are present in the directory.'''

path参数:要获得内容目录的路径

3、创建目录

在python中可以使用os.mkdir()函数创建目录。

os.mkdir(path)

'''帮助文档mkdir(path, mode=511, *, dir_fd=None)

Create a directory.

If dir_fd is not None, it should be a file descriptor open to a directory,

and path should be relative; path will then be relative to that directory.

dir_fd may not be implemented on your platform.

If it is unavailable, using it will raise a NotImplementedError.

The mode argument is ignored on Windows.'''

path参数:要创建目录的路径

os.mkdir()函数只能创建一个目录,也就是说路径参数除了最后面要创建的那个目录不存在,路径之前的所有目录必须存在否则就会出现错误,并且当这个目录存在时也会出现错误“当文件已存在,无法创建该文件”

为此我们可以使用另一个函数os.makedirs()函数来创建多级空目录

os.makedirs(path)

'''帮助文档:makedirs(name, mode=511, exist_ok=False)

makedirs(name [, mode=0o777][, exist_ok=False])

Super-mkdir; create a leaf directory and all intermediate ones. Works like

mkdir, except that any intermediate path segment (not just the rightmost)

will be created if it does not exist. If the target directory already

exists, raise an OSError if exist_ok is False. Otherwise no exception is

raised. This is recursive.'''

path参数:要创建的多级空目录,最后一个目录必须不存在,否则会产生错误”当文件已存在,无法创建该目录“

4、删除目录

在python中可以使用os.rmdir()函数删除目录

os.rmdir(path)

'''帮助文档:rmdir(path, *, dir_fd=None)

Remove a directory.

If dir_fd is not None, it should be a file descriptor open to a directory,

and path should be relative; path will then be relative to that directory.

dir_fd may not be implemented on your platform.

If it is unavailable, using it will raise a NotImplementedError.'''

path参数:要删除的目录的路径,要删除的目录必须是空目录否则会产生错误”目录不是空的“

为此我们可以使用另一个函数os.removedirs()来删除多级空目录,目录必须为空否则会产生错误”目录不是空的“

5、判断是否是目录

在python中可以使用os.path.isdir()函数判断某一路径是否为目录。

os.path.isdir(path)

'''帮助文档:_isdir(path, /)

Return true if the pathname refers to an existing directory.'''

path参数:要进行判断的路径

6、判断是否为文件

在python中可以使用os.path.isfile()函数判断某一路径是否为文件。

os.path.isfile(path)

'''帮助文档:isfile(path)

Test whether a path is a regular file'''

path参数:要进行判断的路径

7、判断是否是绝对路径

os.path.isabs()函数判断路径是否是绝对路径

os.path.isabs(path)

'''帮助文档:isabs(s)

Test whether a path is absolute'''

path参数:要判断的的路径

8、检验路径是否真的存在

os.path.exists()函数判断路径是否真的存在

os.path.exists(path)

'''帮助文档:exists(path)

Test whether a path exists. Returns False for broken symbolic links'''

path参数:要判断的路径

9、分离路径与文件名

os.path.split(path)

'''帮组文档:split(p)

Split a pathname.

Return tuple (head, tail) where tail is everything after the final slash.

Either part may be empty.'''

path参数:要进行分离的路径

10、分离文件扩展名

os.path.splitext(path)

'''帮助文档:splitext(p)

Split the extension from a pathname.

Extension is everything from the last dot to the end, ignoring

leading dots. Returns "(root, ext)"; ext may be empty.'''

path参数:要进行分离的路径

11、获取路径名

os.path.dirname(filename)通过文件的路径只获取路径名

os.path.dirname(filename)

'''帮助文档:dirname(p)

Returns the directory component of a pathname'''

path参数:文件的具体路径

12、获取文件名

os.path.basename(filename)通过路径获取文件名

os.path.basename(filename)

'''帮助文档:basename(p)

Returns the final component of a pathname'''

path参数:文件的具体路径

13、读取和设置环境变量

os.getenv()函数获取环境变量os.putenv()设置环境变量

os.getenv()

'''帮助文档:getenv(key, default=None)

Get an environment variable, return None if it doesn't exist.

The optional second argument can specify an alternate default.

key, default and the result are str.'''

os.putenv()

'''帮助文档:putenv(name, value, /)

Change or add an environment variable.'''

14、给出当前平台使用的行终止符

15、指示你正在使用的平台

os.name()函数指示你当前使用的平台

windows平台为’nt‘

16、获取文件属性

os.stat(file)函数获取文件的属性

os.stat()

'''帮助文档:stat(path, *, dir_fd=None, follow_symlinks=True)

Perform a stat system call on the given path.

path

Path to be examined; can be string, bytes, a path-like object or

open-file-descriptor int.

dir_fd

If not None, it should be a file descriptor open to a directory,

and path should be a relative string; path will then be relative to

that directory.

follow_symlinks

If False, and the last element of the path is a symbolic link,

stat will examine the symbolic link itself instead of the file

the link points to.

dir_fd and follow_symlinks may not be implemented

on your platform. If they are unavailable, using them will raise a

NotImplementedError.'''

17、重命名文件或者目录

os.rename(old, new)函数重命名文件或者目录

os.rename(old, new)

'''帮助文档:rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

Rename a file or directory.

If either src_dir_fd or dst_dir_fd is not None, it should be a file

descriptor open to a directory, and the respective path string (src or dst)

should be relative; the path will then be relative to that directory.

src_dir_fd and dst_dir_fd, may not be implemented on your platform.

If they are unavailable, using them will raise a NotImplementedError.'''

18、获得文件大小

os.path.getsize()

'''帮助文档:getsize(filename)

Return the size of a file, reported by os.stat().'''

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/472525.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第十七节(is-a 、is-like-a 、has-a,包和 import )

is - a 类与类之间的继承关系;is - like - a 类与接口之间的关系;has - a 关联关系; public class Animal{public void method01();}// 类与类之间的关系class Dog extends Animal{ // Dog is a Animal} /// public interface I{public void…

quartz获取开始结束时间_Springboot集成quartz

Quartz 是一个完全由 Java 编写的开源作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。本文描述在springboot 2.x环境下怎么集成quartz。一、添加quartz到项目中在pom.xml中加入 <dependency>特别注意application入口类的注解&#xff0c;这里一定…

linux 添加本地磁盘,XenServer如何添加本地存储

在一次测试中&#xff0c;发现本地有两块磁盘&#xff0c;但是只有一块磁盘在XenServer中显示出来&#xff0c;另外一块没有显示。本地只有一个Local storage。查询KB后&#xff0c;发现XenServer可以添加多块本地存储。详情&#xff0c;请见KB&#xff1a;CTX121313详细添加如…

流畅的Python 5. 函数

文章目录1. 函数对象2. 高阶函数3. 匿名函数4. 可调用函数5. 定位参数、仅限关键字参数6. 获取参数信息7. 函数注解8. 支持函数式编程的包1. 函数对象 def factorial(n):returns n! n的阶乘return 1 if n < 2 else n * factorial(n - 1)print(factorial(42)) print(factori…

python方向键键值_python字典键值对的添加和遍历方法

添加键值对 首先定义一个空字典 >>> dic{} 直接对字典中不存在的key进行赋值来添加 >>> dic[name]zhangsan >>> dic {name: zhangsan} 如果key或value都是变量也可以用这种方法 >>> keyage >>> value30 >>> dic[key]val…

无穷大正整数 python_python模块:数字处理

http://blog.csdn.net/pipisorry/article/details/37055183python数字处理简介数字类型python没有unsighed int&#xff1a;The Python int is an abstraction of an integer value, not a direct access to a fixed-byte-size integer.不过int还是当成sighed int处理的&#x…

linux主机基本情况,查看linux主机系统基本信息.pdf

查看linux 主机系统的基本信息一、 硬件信息1. CPUa. Cat /proc/cpuinfo例&#xff1a;[rootlinux victor]# cat /proc/cpuinfoprocessor : 0vendor_id : GenuineIntelcpu family : 6model : 13model name : Intel(R) Celeron(R) M processor 1.50GHzstepping : 8cpu MHz : 150…

LeetCode 1805. 字符串中不同整数的数目(哈希set)

文章目录1. 题目2. 解题1. 题目 给你一个字符串 word &#xff0c;该字符串由数字和小写英文字母组成。 请你用空格替换每个不是数字的字符。 例如&#xff0c;“a123bc34d8ef34” 将会变成 " 123 34 8 34" 。 注意&#xff0c;剩下的这些整数间至少要用一个空格隔…

Android线程之异步消息处理机制(二)——Message、Handler、MessageQueue和Looper

异步消息处理机制解析 Android中的异步消息处理主要有四个部分组成&#xff0c;Message、Handler、MessageQueue和Looper。 1、Message Message是在线程之间传递的消息&#xff0c;它可以在内部携带少量的信息&#xff0c;用于在不同线程之间交换数据。上个例子中就使用了Messa…

linux 树状结构图,linux下tree指令的用法, 树状图列出目录, 树状图逐级列出目录...

tree命令&#xff0c;主要功能是创建文件列表&#xff0c;将所有文件以树的形式列出来linux下的tree就比较强大了&#xff0c;但一般系统并不自带这个命令&#xff0c;需要手动下载安装,安装sudo apt install tree## or using yum# yum -y install tree语法tree[-aACdDfFgilnNp…

映射表map(平衡二叉树实现)_手动实现Java集合容器之TreeMap(上)

上一篇我们手写了HashMap&#xff0c;还有一个很重要的Map的实现类TreeMap。打开源码第一句话&#xff1a;* A Red-Black tree based {link NavigableMap} implementation.TreeMap是一个基于红黑树的实现。对红黑树没有了解怎么办&#xff0c;那就先搞清楚红黑树的原理。只要理…

wltc循环多少公里_原来所有车都烧机油!但是烧多少才算正常你知道吗?

点击上方“腾讯汽车”关注我们&#xff0c;最新汽车资讯&#xff0c;最方便的用车常识还有最萌的小编都在这里啦&#xff01;最为当今汽车用户最为关心的问题&#xff0c;烧机油现象被很多用户当做引擎是好是坏的重要标准。但根据机油在引擎内冷却及清理引擎内杂质的循环机制来…

LeetCode 1806. 还原排列的最少操作步数(模拟)

文章目录1. 题目2. 解题1. 题目 给你一个偶数 n​​​​​​ &#xff0c;已知存在一个长度为 n 的排列 perm &#xff0c;其中 perm[i] i​&#xff08;下标 从 0 开始 计数&#xff09;。 一步操作中&#xff0c;你将创建一个新数组 arr &#xff0c;对于每个 i &#xff…

linux 间隔定时器,Linux间隔定时器的使用 探索一

2011年1月17日之前看《高级Unix编程》说有基本定时器与高级定时器之分好像基本定时器不符合我的要求&#xff0c;那么就先来个高级的吧。写个代码看看会有什么发生&#xff1a;2011年1月18日看下timer_create函数intt1;timer_t tm_id;//timer_t其实是个long型t1 timer_create(…

游标操作 for Oracle

游标用来处理从数据库中检索的多行记录&#xff08;使用SELECT语句&#xff09;。利用游标&#xff0c;程序可以逐个地处理和遍历一次检索返回的整个记录集。 为了处理SQL语句&#xff0c;Oracle将在内存中分配一个区域&#xff0c;这就是上下文区。这个区包含了已经处理完的行…

python3经典实例_Python3十大经典错误及解决办法

接触了很多Python爱好者&#xff0c;有初学者&#xff0c;亦有转行人。不论大家学习Python的目的是什么&#xff0c;总之&#xff0c;学习Python前期写出来的代码不报错就是极好的。下面&#xff0c;严小样儿为大家罗列出Python3十大经典错误及解决办法&#xff0c;供大家学习。…

python谱聚类算法_谱聚类Spectral clustering(SC)

在之前的文章里&#xff0c;介绍了比较传统的K-Means聚类、Affinity Propagation(AP)聚类、比K-Means更快的Mini Batch K-Means聚类以及混合高斯模型Gaussian Mixture Model(GMM)等聚类算法&#xff0c;今天介绍一个比较近代的一类算法——Spectral Clustering 中文通常称为“谱…

LeetCode 1807. 替换字符串中的括号内容(哈希map)

文章目录1. 题目2. 解题1. 题目 给你一个字符串 s &#xff0c;它包含一些括号对&#xff0c;每个括号中包含一个 非空 的键。 比方说&#xff0c;字符串 "(name)is(age)yearsold" 中&#xff0c;有 两个 括号对&#xff0c;分别包含键 “name” 和 “age” 。 你知…

bootice.exe linux 启动盘,下载BOOTICE来把你的U盘做成启动盘

为了方便维护电脑&#xff0c;需要制作一个合适的U盘启动盘。网上制作U盘启动盘的工具也有很多&#xff0c;我下面使用bootice这个U盘启动盘制作工具来制作U盘启动盘。下载BOOTICE1、BOOTICE>分区管理G&#xff0c;对U盘进行格式化&#xff0c;FAT16&#xff0c;卷标设置为G…

数据类型的选择

1、CHAR与VARCHAR CHAR与VARCHAR类型类似&#xff0c;都用来存储字符串。 CHAR&#xff1a;固定长度&#xff0c;处理速度较VARCHAR快&#xff0c;但浪费空间。 VARCHAR&#xff1a;可变长度 1 CHAR(4)和VARCHAR(4)列检索的值并不总相同&#xff0c;CHAR列删除了尾部的空格 2、…