第五章 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语句

相关推荐
l1t20 分钟前
用parser_tools插件来解析SQL语句
数据库·sql·插件·duckdb
咖啡续命又一天24 分钟前
python 自动化采集 ChromeDriver 安装
开发语言·python·自动化
代码程序猿RIP29 分钟前
【SQLite 库】sqlite3_open_v2
jvm·oracle·sqlite
TDengine (老段)38 分钟前
TDengine 数学函数 ABS() 用户手册
大数据·数据库·sql·物联网·时序数据库·tdengine·涛思数据
lypzcgf40 分钟前
Coze源码分析-资源库-编辑数据库-后端源码-安全与错误处理
数据库·安全·系统架构·coze·coze源码分析·ai应用平台·agent平台
阿湯哥40 分钟前
Redis数据库隔离业务缓存对查询性能的影响分析
数据库·redis·缓存
麦兜*40 分钟前
Redis 7.2 新特性实战:Client-Side Caching(客户端缓存)如何大幅降低延迟?
数据库·spring boot·redis·spring·spring cloud·缓存·tomcat
web安全工具库1 小时前
Linux 高手进阶:Vim 核心模式与分屏操作详解
linux·运维·服务器·前端·数据库
松果集1 小时前
【1】数据类型2
python