python中os库的函数使用
作者:YMWM_ 时间:2022-05-03 22:16:57
介绍
os模块是Python和操作系统进行交互的一个接口,它提供了许多操作文件及文件夹的函数。可以用于文件名、文件路径、文件夹相关的操作。
本博客记录python中os库的一些函数使用。
1 listdir(path: str)
listdir()
函数输入一个目录,返回该目录下的所有文件夹名称和文件名称。注意是名称而非路径。
举例,比如在路径D:\tmp
下有如下文件,
那么,os.listdir('D:\\tmp')
返回的内容为,
['文件1.txt', '文件2.txt', '文件3.txt', '文件夹1', '文件夹2', '文件夹3']
代码为,
import os
path = 'D:\\tmp'
files = os.listdir(path)
print(files)
2 path.isdir(path: str)
path.isdir()
函数返回布尔值,表示输入的路径是否为文件夹,如果是返回True
,否则返回False
。
举例,比如path.isdir('D:\\tmp\\文件夹1')
返回True
,而path.isdir('D:\\tmp\\文件1.txt')
返回False
。
代码如下,
import os
if os.path.isdir('D:\\tmp\\文件夹1') == True:
print('True')
if os.path.isdir('D:\\tmp\\文件1.txt') == False:
print('False')
输出为,
TrueFalse
3 path.isfile(path: str)
path.isfile()
函数返回布尔值,表示输入的路径是否为文件,如果是返回True
,否则返回False
。
举例,比如path.isfile('D:\\tmp\\文件夹1')
返回False
,而path.isdir('D:\\tmp\\文件1.txt')
返回True
。
代码如下,
import os
if os.path.isfile('D:\\tmp\\文件夹1') == False:
print('False')
if os.path.isfile('D:\\tmp\\文件1.txt') == True:
print('True')
输出为,
False
True
4 path.join(path: str, file: str)
path.join()
函数拼接两个路径,在windows下拼接符为\\
,因此path.join(path, file)
等价于path + '\\' + file
。但不同系统的拼接符是不一样的,因此使用path.join()
函数拼接两个路径会更鲁棒。
代码如下,
import os
path = 'D:\\tmp'
for file in os.listdir(path):
filename = file
filepath = os.path.join(path, filename)
print(f'filename = {filename}, filepath = {filepath}')
输出为,
filename = 文件1.txt, filepath = D:\tmp\文件1.txt
filename = 文件2.txt, filepath = D:\tmp\文件2.txt
filename = 文件3.txt, filepath = D:\tmp\文件3.txt
filename = 文件夹1, filepath = D:\tmp\文件夹1
filename = 文件夹2, filepath = D:\tmp\文件夹2
filename = 文件夹3, filepath = D:\tmp\文件夹3
5 path.getsize(path: str)
path.getsize()
函数返回输入文件的大小,单位是字节(Byte)。如果输入为文件夹的话,返回0。
举例,比如path.getsize('D:\\tmp\\文件夹1')
返回0,path.getsize('D:\\tmp\\文件1.txt')
返回文件1.txt的大小。
代码如下,
import os
size1 = os.path.getsize('D:\\tmp\\文件夹1')
size2 = os.path.getsize('D:\\tmp\\文件1.txt')
print(f'size1 = {size1}字节, size2 = {size2}字节')
输出为,
size1 = 0字节, size2 = 8字节
来源:https://blog.csdn.net/YMWM_/article/details/127541442
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解析:正确的理解SQL Server和XML支持
解决usageerror: line magic function "%%time" not found问题
![](https://img.aspxhome.com/file/2023/6/115626_0s.jpg)
Python使用Chrome插件实现爬虫过程图解
![](https://img.aspxhome.com/file/2023/4/78814_0s.png)
django与小程序实现登录验证功能的示例代码
PHP中phar包的使用教程
Python中三种花式打印的示例详解
微信小程序实现富文本图片宽度自适应的方法
![](https://img.aspxhome.com/file/2023/5/56025_0s.jpg)
python 构造三维全零数组的方法
asp读取数据库中数据到数组的类
php Exception异常处理详解
ASP连接access和mssql数据库的全能代码
Python游戏开发之Pygame使用的最全教程分享
详解python的xlwings库读写excel操作总结
Python 3 使用Pillow生成漂亮的分形树图片
![](https://img.aspxhome.com/file/2023/2/109962_0s.jpg)
python实现AdaBoost算法的示例
Python控制线程和函数超时处理
![](https://img.aspxhome.com/file/2023/2/77802_0s.png)
详解python使用canvas实现移动并绑定键盘
![](https://img.aspxhome.com/file/2023/8/68368_0s.png)
浅谈python 类方法/静态方法
python 解决flask 图片在线浏览或者直接下载的问题
python TK库简单应用(实时显示子进程输出)
![](https://img.aspxhome.com/file/2023/2/78812_0s.png)