模块介绍
os(操作系统)模块实现对文件和目录的一系列操作。对于文件来说,包括文件的读写、文件的打开关闭、新建文件、删除文件、文件重命名、文件复制、获取文件属性、获取文件路径等操作;对于目录来说,包括目录的创建、删除、获取当前工作目录等操作。
模块方法
1、os.open函数
os.open(file, flags[, mode])
open函数以指定方式(只读、只写、读写等)打开一个文件,返回一个文件描述符,该描述符为一个int整数。
import os
# 以只读方式打开文件,返回一个文件描述符,int类型
fd_1 = os.open("demo.txt", os.O_RDONLY)
# 以只写方式打开文件(文件指针在文件头)
fd_2 = os.open("demo.txt", os.O_WRONLY)
# 以读写方式打开文件(文件指针在文件头)
fd_3 = os.open("demo.txt", os.O_RDWR)
# 以追加方式打开文件(文件指针在文件尾)
fd_4 = os.open("demo.txt", os.O_APPEND)
# 打开文件时,如果文件不存在,则创建一个新文件并打开
fd_5 = os.open("demo.txt", os.O_CREAT)
# 方式之间可以组合
fd_6 = os.open("demo.txt", os.O_RDONLY | os.O_WRONLY)
2、os.close、os.closerange函数
os.close(fd);
close函数关闭一个文件描述符对应的文件。
os.closerange(fd_low, fd_high)
closerange函数根据文件描述的范围关闭多个文件。
import os
fd_1 = os.open("demo.txt", os.O_RDONLY)
fd_2 = os.open("demo.txt", os.O_WRONLY)
fd_3 = os.open("demo.txt", os.O_RDWR)
fd_4 = os.open("demo.txt", os.O_APPEND)
# 关闭文件1,单个文件
os.close(fd_1)
# 关闭文件2、文件3、文件4多个文件
os.closerange(fd_2, fd_4)
3、os.read函数
os.read(fd,n)
read函数从文件描述符对应的文件中读取n个字节的数据,包括“\n","\t"等转义字符。
import os
# 打开文件
fd = os.open("demo.txt", os.O_RDWR)
# 读取前100个字节数据
text = os.read(fd, 100)
# 关闭文件
os.close(fd)
4、os.write函数
os.write(fd, str)
write函数将字符串对应的字节数组对象写入到文件中,返回一个整数,表示写入成功的字符串长度。
import os
# 以追加写方式打开文件
fd = os.open("demo.txt", os.O_APPEND | os.O_RDWR)
# 写入数据到文件中
text = "this is a text"
b_text = bytes(text, "UTF-8")
n = os.write(fd, b_text)
# 关闭文件
os.close(fd)
5、os.remove函数
os.remove(path)
remove函数删除指定路径下的文件。
6、os.rename、os.renames函数
os.rename(src, dst)
rename函数用于命名文件或目录,从 src 到 dst,如果dst是一个存在的目录, 将抛出OSError。
os.renames(old, new)
renames函数用于递归重命名目录或文件。类似rename()。
7、os.getcwd函数
os.getcwd()
getcwd函数返回当前工作目录,也就是运行的程序所在的目录。
8、os.listdir函数
os.listdir(path)
listdir函数列出当前路径所在目录下的所有的文件和目录,返回一个列表,这个列表以字母顺序排序。
import os
# 列出当前工作目录下的所有文件
file_list = os.listdir(os.getcwd())
9、os.mkdir、os.rmdir函数
os.mkdir(path[, mode])
mkdir函数用于以数字权限模式创建目录。默认的模式为 0777 (八进制)。
如果目录有多级,则创建最后一级,如果最后一级目录的上级目录有不存在的,则会抛出一个 OSError。
os.rmdir(path)
删除path指定的空目录,如果目录非空,则抛出一个OSError异常。
import os
# 当前目录下创建一个子目录
os.makedirs("./demo1")
# 删除当前目录下的demo1子目录
os.rmdir("./demo1")
模块使用
使用import os来导入os模块来使用模块相关函数。