第五章 Python文件操作

系列文章目录
第一章 Python 基础知识
第二章 python 字符串处理
第三章 python 数据类型
第四章 python 运算符与流程控制
第五章 python 文件操作
第六章 python 函数
第七章 python 常用内建函数
第八章 python 类(面向对象编程)
第九章 python 异常处理
第十章 python 自定义模块及导入方法
第十一章 python 常用标准库
第十二章 python 正则表达式
第十三章 python 操作数据库



open()函数

要想读取文件(如txt、csv等),第一步要用open()内建函数打开文件,它会返回一个文件对象,这个对象 拥有read()、write()、close()等方法。

语法:
open(file,mode=‘r’,encoding=None)

file:打开文件的路径
mode(可选):打开文件的模式,入只读、追加、写入等
r: 只读
w: 只写
a: 在原有的内容的基础上追加内容(末尾
w+: 读写
如果需要以字节(二进制)形式读取文件,只需要在mode值追加’b’即可,例如:wb

文件对象操作

f = open(‘test.txt’)

方法描述
f.read([size])读取size字节,当未指定或给负值时,读取剩余所有的字节,作为字符串返回
f.readline([size])从文件中读取下一行,作为字符串返回。如果指定size则返回size字节
f.readlines([size])读取size字节,当未指定或给负值时,读取剩余所有的字节,作为列表返回
f.write(str)
f.flush
写字符串到文件
刷新缓冲区到磁盘
f.seek(offset[, whence=0])在文件中移动指针,从whence(0代表文件起始位置,默认。1代表当前位置。 2代表文件末尾)偏移offset个字节
f.tell()当前文件中的位置(指针)
f.close()关闭文件

示例:遍历打印每一行
f = open(‘computer.txt’)
for line in f:
print(line.strip(‘\n’)) # 去掉换行符

f = open('computer.txt',mode='r',encoding='utf8')
# 读取所有内容
print(f.read())

# 读取指定字节
# print(f.read(4))

# 读取下一行
# print(f.readline())
# print(f.readline())
# print(f.readline())

# 读取所有内容返回列表
# print(f.readlines())

# 增加音响
f = open('computer.txt',mode='a',encoding='utf8')
f.write('\n音响')
f.flush
# print(f.read())
# for i in f:
#     print(i.strip('\n'))
f.close()
f.close()

with语句

with语句:不管在处理文件过程中是否发生异常,都能保证 with 语句 执行完毕后已经关闭了打开的文件句柄。
示例:
with open(“computer.txt”,encoding=“utf8”) as f:
data = f.read()
print(data)

# 增加音响
print('====原始文件')
with open('computer.txt',mode='r',encoding='utf8') as d:
    print(d.read())
print('====增加上帝')
with open('computer.txt',mode='a',encoding='utf8') as f:
    f.write('\n上帝')
    f.flush
print('====增加后')
with open('computer.txt',mode='r',encoding='utf8') as g:
    print(g.read())

在这里插入图片描述

# 增加音响
print('====原始文件')
with open('computer.txt',mode='r',encoding='utf8') as d:
    print(d.read())

computer = ["主机","显示器","键盘","音响"]
with open('computer.txt',encoding=None,mode='w+') as f:
    for i in computer:
        f.write("\n" + i)
    f.flush

print('====增加后')
with open('computer.txt',mode='r',encoding='utf8') as g:
    print(g.read())

在这里插入图片描述


总结

以上就是今天学习的内容,本文学习了open以及文件对象还有with语句

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XMYX-0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值