【Python】第十六部分 文件读写操作
文章目录
16. 文件读写操作
16.1 常用文件打开模式
# 打开文件 open(文件名,文件打开模式)
# r : 只读模式
file = open('a.txt', 'r')
print(file.read())
# w : 写模式 会覆盖之前所写的全部内容,如果文件不存在则创建,反之不创建
file = open('a.txt', 'w')
print(file.write('hello!'))
# a : 追加模式 如果文件存在则追加到末尾,如果不存在则创建新文件
file = open('a.txt', 'a')
print(file.write('我是追加的数据'))
# + :必须配合 a 才可以使用 a+ : 表示以读写的模式
file = open('a.txt', 'a+')
print(file.write('我是追加的数据'))
# b : 以二进制的模式打开文件,必须配合 rb,wb才可以使用
origin = open('hudie.png', 'rb') # 以二进制进行读取
open('copyhudie.png', 'wb').write(origin.read()) # 以二进制进行写入
# 最后记得关闭
file.close()
origin.close()
16.2 读取文件
f = open('file.txt', 'r', encoding='utf-8')
# 读取全部的内容
f.read()
# 读取全部行,封装到列表中
f.readlines()
# 读取一行,可以多次调用读取多行
f.readline()
# 文件关闭操作
f.close()
16.3 写入文件
f = open('file.txt', 'w', encoding='utf-8')
# 这一步只是将我们的内容写入到内存中
f.write('\nhello world!')
# flush刷新 将内存中积攒的内容写入到硬盘文件中
f.flush()
# close方法其实是内置了flush功能的
f.close()
16.4 with 语句
作用: with语句可以自动管理上下文资源,不论什么原因跳出with语句都能够保证文件的正常关闭,以此来达到释放资源的目的,这样就不用写 file.close()
with open('hudie.png', 'rb') as origin:
with open('copyhudie.png', 'wb') as copy_file:
copy_file.write(origin.read())
16.5 os模块
# os模块 它是与操作系统相关的模块
import os
# 获取当前的工作目录
file = os.getcwd()
print(file) # E:\PythonProject
# 改变当前的工作目录
os.chdir('E:\Test')
# 创建目录
os.mkdir('Test')
# 创建多层目录
os.makedirs('Test/hello/world')
# 删除目录
os.rmdir('Test')
# 删除多层目录
os.removedirs('Test/hello/world')
# 查看指定路径下的文件和目录
print(os.listdir('./venv'))
print(os.scandir('./venv'))
# 删除文件
os.remove('test.py')
# 重命名文件
os.rename('oldname', 'newname')
# 打开记事本
os.system('notepad.exe')
# 打开计算器
os.system('calc.exe')
# 打开指定软件
os.startfile('C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe')
16.6 文件的遍历
import os
# 遍历文件或者目录
listfile = os.listdir('../learn')
for file in listfile:
# 将路径和文件进行拼接
print(os.path.join(os.getcwd(), file))
import os
filelist = os.scandir('../learn')
for file in filelist:
# 和os.listdir()不同的是:遍历的每一项都是对象
print(os.path.join(os.getcwd(), file.name))
拓展
import os
from datetime import datetime
filelist = os.scandir('../learn')
for file in filelist:
# stat可以拿到文件的详细信息
print(file.stat())
# 获取文件的创建时间
print(datetime.fromtimestamp(file.stat().st_ctime))
16.7 os.path模块
import os.path
# 获取文件的绝对路径
print(os.path.abspath('a.txt')) # E:\PythonProject\a.txt
# 判断文件是否存在
print(os.path.exists('a.txt'), os.path.exists('b.txt')) # True False
# 分离文件路径和文件名
print(os.path.split('E:\\PythonProject\\a.txt'))
# ('E:\\PythonProject', 'a.txt')
# 分离文件名和扩展名
print(os.path.splitext('a.txt'))
# ('a', '.txt')
# 将目录和文件名进行拼接
print(os.path.join('E:\\new\\', 'b.txt'))
# E:\new\b.txt
# 获取文件基本路径
print(os.path.dirname('E:\\PythonProject\\hello\\world\\a.txt'))
# E:\PythonProject\hello\world
# 获取文件名
print(os.path.basename('E:\\PythonProject\\hello\\world\\a.txt'))
# a.txt
# 判断是否为目录(文件夹)
print(os.path.isdir('E:\\PythonProject\\hello\\world\\a.txt')) # False
# 判断是否为文件
print(os.path.isfile('E:\\PythonProject\\hello\\world\\a.txt')) # True
16.8 案例
# 案例 获取目录下后缀名为 .py
import os
path = os.getcwd()
listFile = os.listdir(path)
for item in listFile:
if item.endswith('.py'):
priath,fileItem))
# 获取指定目录下的文件路径
import os
path = os.getcwd()
listFile = os.walk(path) # 得到的是一个对象
# 遍历
for dirpath, dirname, filename in listFile:
'''
dirpath 当前路径
dirname 当前路径下目录
filename 当前路径下的文件
'''
for dirItem in dirname:
print(os.path.join(dirpath, dirItem))
for fileItem in filename:
print(os.path.join(dirpath,fileItem))
总结
以上就是今天要讲的内容,希望对大家有所帮助!!!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/82833.html