python3文件操作
1 open() 方法
- python中的文件操作主要通过内置的open() 函数来完成,该函数用于打开文件,并返回一个文件对象。通过文件对象,可以进行各种文件操作,如读取、写入、关闭等。
- 在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。
- 注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。
- open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)
- 语法:open(file, mode)
- 常见模式:
- ‘r’:以读模式打开文件(默认)
- ‘w’:以写模式打开文件(文件存在清空文件内容,不存在创建文件)
- ‘a’:以追加模式打开文件(文件存在则追加内容,不存在则创建新文件)
- ‘b’:以二进制模式打开文件
- ‘+’:以读写模式打开文件
1.1 open() 方法完整语法格式
- open(file,mode=‘r’,buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None)
- 参数说明
- file: 必需,文件路径(相对或者绝对路径)
- mode: 可选,文件打开模式
- buffering: 设置缓冲
- encoding: 一般使用utf8
- errors: 报错级别
- newline: 区分换行符
- closefd: 传入的file参数类型
- opener: 设置自定义开启器,开启器的返回值必须是一个打开的文件描述符。
- 文件操作的步骤:
- 打开文件
- 操作文件内容(写操作需要刷新缓存区)
- 关闭文件
1.2 示例
- r:读模式
# encoding="utf-8":指定编码格式
file1=open("D:/333/1.txt","r",encoding="utf-8")
# 读取文件内容
context1=file1.read()
print(context1)
# 关闭文件
file1.close()# seek():修改指针位置
file1=open("D:/333/1.txt","r",encoding="utf-8")
# 从指定位置开始读取文件内容
file1.seek(3)
context1=file1.read()
print(context1)
# 指针不会自动回到开头,要修改指针位置才能再次读取
file1.seek(0)
context1=file1.read()
print(context1)
file1.close()
- w:写模式
file1=open("D:/333/1.txt","w",encoding="utf-8")
str1="I am python"
# 向文件中写入内容
file1.write(str1)
# 刷新缓冲区
file1.flush()
file1.close()
- a:追加模式
file1=open("D:/333/1.txt","a",encoding="utf-8")
str1="""
hello world"""
file1.write(str1)
file1.flush()
file1.close()
- b:二进制模式
file1=open("D:/333/1.txt","rb",encoding="utf-8")
context1=file1.read()
print(context1)
file1.close()
- a+:读写模式(追加)
file1=open("D:/333/1.txt","a+",encoding="utf-8")
str1="""
hi hi hi"""
file1.write(str1)
file1.flush()
# 移动文件指针至文件的开头,读取文件内容
file1.seek(0)
context1=file1.read()
print(context1)
file1.close()
- 使用相对路径
# 查看当前工作目录
import os
print('当前工作目录是:',os.getcwd())
# 使用相对路径打开文件
file1=open("../../333/1.txt","r",encoding="utf-8")
context1=file1.read()
print(context1)
file1.close()
1.3 with open 语句
- 确保文件在操作完成后自动关闭,避免资源泄露。
- 语法:with open(file, mode) as name
- 示例:
with open("D:/333/1.txt","r",encoding="utf-8") as file1:context1=file1.read()print(context1)
1.4 字节流与字符流
- 字符流是通用的类型,对文本文件和非文本文件都适用
- 字符流只适用与文本文件,速度更快
- 示例:
# 复制文本文件
with open("D:/333/1.txt","r",encoding="utf-8") as file1:with open("D:/333/2.txt","w",encoding="utf-8") as file2:context1=file1.read()file2.write(context1)file2.flush()
# 复制非文本文件
with open("D:/333/HT.jpg","rb") as file1:with open("D:/333/HT2.jpg","wb") as file2:context1=file1.read()file2.write(context1)file2.flush()
1.5 不同的读取方式
- read([size]):从文件当前位置起读取size个字节,若无参数size,则表示读取至文件结束为止,它返回为字符串对象。
with open("D:/333/1.txt","r",encoding="utf-8") as file1:context1=file1.read()print(context1)print(type(context1))
- readline():每次读出一行内容,所以读取时占用内存小,比较适合大文件,该方法返回一个字符串对象。
with open("D:/333/1.txt","r",encoding="utf-8") as file1:while True:line=file1.readline()print(line)print(type(line))if not line:break
- readlines():读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素,但读取大文件会比较占内存。
with open("D:/333/1.txt","r",encoding="utf-8") as file1:lines=file1.readlines()print(lines)print(type(lines))
1.6 文件操作应用场景
- 配置文件读取与写入
读取和修改配置文件是文件操作的常见应用场景,可以将程序的配置信息存储在文件中,通过文件操作进行读取和修改。 - 日志记录
将程序的运行状态、错误信息等记录到日志文件中,便于调试和维护。
2 OS模块
- 在python中,os 模块是一个非常重要的内置模块,提供了非常丰富的方法用来处理文件和目录。
- os 模块提供了与操作系统交互的多种功能。允许执行文件和目录操作、获取环境变量、执行系统命令等。
import os
# 获取工作目录
print(os.getcwd())
2.1 os.mkdir()
- 用于创建目录
import os
os.mkdir("day1")
os.mkdir("day2")
# 创建空文件
file1=open("./day1/3.txt","w",encoding="utf-8")
file1.close()
2.2 os.rename()
- 用于重命名文件或目录
import os
os.rename("day2","day3")
os.rename("day1/3.txt","day1/1.txt")
2.3 os.rmdir()
-用于删除目录
import os
# 只能删除空目录
os.rmdir("day3")
2.4 os.remove()
- 用于删除文件
import os
os.remove("day1/1.txt")
2.5 os.makedirs()
- 创建嵌套目录
import os
os.makedirs("9/3/1")
2.6 os.listdir()
- 列出当前目录下所有文件和目录
import os
print(os.listdir())
2.7 os.chdir()
- 切换工作目录
import os
os.chdir("day1")
print(os.getcwd())
2.8 环境变量操作
- 获取环境变量
import os
print(os.environ.get("TEMP"))
- 设置环境变量
import os
os.environ.get["new_avr"]="value"
2.9 执行系统命令
import os
os.system("mkdir day0")
# 获取当前操作系统
print(os.name)
import os
# 获取当前操作系统详细信息
print(os.system("systeminfo"))
2.10 文件权限
- 查看文件权限
import os
status=os.stat("D:/333/1.txt")
print(status.st_mode)
- 修改文件权限
import os
os.chmod("D:/333/1.txt",0o755)
2.11 遍历目录树
- os.walk() 方法可以创建一个生成器,用以生成所要查找的目录及其子目录下的所有文件。
- 语法:os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]])
- 示例:
import os
for root, dirs, files in os.walk(os.getcwd()):print(root, dirs, files)
2.12 os.path模块
- os.path 模块是 Python 标准库中 os 模块的一部分,专门用于操作和处理文件路径。
- os.path 提供了一组强大的工具来对文件和目录路径进行各种操作,例如获取文件名、判断路径是否存在、路径拼接、路径规范化等。
- os.path 模块在跨平台操作系统中表现良好,使得同一段代码能够在不同操作系统(如 Windows、Linux、macOS)上运行时处理路径相关问题。
- 示例:
# 获取文件创建时间
print(os.path.getctime('D:/333/1.txt'))
# 获取文件修改时间
print(os.path.getmtime('D:/333/1.txt'))
# 获取文件访问时间
print(os.path.getatime('D:/333/1.txt'))
# 判断文件或目录是否存在
print(os.path.exists('D:/333/1.txt'))
print(os.path.exists('D:/333/0.txt'))# 判断是否为目录
print(os.path.isdir('D:/333/1.txt'))
# 判断是否为文件
print(os.path.isfile('D:/333/1.txt'))
# 获取文件大小
print(os.path.getsize('D:/333/HT.jpg'))# 获取文件名
print(os.path.basename('D:/333/HT.jpg'))# 获取绝对路径
print(os.path.abspath('D:/333/HT.jpg'))
2.13 shutil
import shutil
# 复制文件
shutil.copy("D:/333/1.txt","D:/333/A/111.txt")
# 移动文件
shutil.move("D:/333/A/111.txt","D:/333/B/111.txt")
# 删除目录及目录中所有内容
shutil.rmtree("D:/333/B/")
# 复制目录及目录中所有内容
shutil.copytree("D:/333/A","D:/333/B")