第五章 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')) # 去掉换行符

python 复制代码
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)

python 复制代码
# 增加音响
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())
python 复制代码
# 增加音响
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语句

相关推荐
孟健3 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞5 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
倔强的石头_5 小时前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库
曲幽7 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程12 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪12 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook12 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img