系列文章目录
第一章 Python 基础知识
第二章 python 字符串处理
第三章 python 数据类型
第四章 python 运算符与流程控制
第五章 python 文件操作
第六章 python 函数
第七章 python 常用内建函数
第八章 python 类(面向对象编程)
第九章 python 异常处理
第十章 python 自定义模块及导入方法
第十一章 python 常用标准库
第十二章 python 正则表达式
第十三章 python 操作数据库
文章目录
open()函数
文件对象操作
方法 | 描述 |
---|---|
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',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语句
# 增加音响
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语句