Python文件读写open函数详解
作者:匿名V5程序员 时间:2021-05-25 07:46:09
前言:
open()函数的定义:def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
常用的参数有 file、mode、encoding
file是文件名称, mode是文件的打开方式、encoding是文件编码格式
mode常见的有 只读模式®、写入模式(w)、追加模式(a)、读写模式(r+/w+/a+)
r+要求文件必须存在;锚点置于末行末位字符处
w+文件不存在时新建,文件存在时将文件内容清空,锚点置于首行首字符处
a+文件不存在时新建,文件存在时打开文件,将锚点置于末行末位字符处
filename = 'test.txt'
# 以只读方式打开test.txt文件
fd = open(filename, 'r', encoding='utf-8')
# fd.read(self, n) 按指定的长度读取文件内容,为空则读取全部内容
lines = fd.read()
print(lines)
fd.close()
print('------------------read------------------------')
# 以写入模式打开test.txt文件
fd = open(filename, 'w', encoding='utf-8')
# fd.write(self, str) 将str写入文件
lines_w = fd.write('java\nPython\tGolang')
print(lines_w)
fd.close()
print('------------------write------------------------')
# 以追加模式打开文件
fd = open(filename, 'a', encoding='utf-8')
lines_a = fd.write('java\nPython\tGolang')
print(lines_a)
fd.close()
print('------------------append------------------------')
# 以读写模式打开文件(r+)
fd = open(filename, 'r+', encoding='utf-8')
print(fd.read())
lines_str = fd.write('java\nPython\tGolang')
print(fd.read())
fd.close()
print('------------------readWrite------------------------')
# 以读写模式打开文件(w+)
fd = open(filename, 'w+', encoding='utf-8')
lines_str = fd.write('java\nPython\tGolang')
print(fd.read()) # 文件打开时清空文件内容,虽然写入了文件,但未保存,因此读取文件为空
fd.close()
print('------------------readWrite------------------------')
# 以读写模式打开文件(a+)
fd = open(filename, 'a+', encoding='utf-8')
print(fd.read())
# 按行读取
print(fd.readlines(2))
lines_str = fd.write('java\nPython\tGolang')
print(fd.read())
fd.close()
print('------------------readWrite------------------------')
来源:https://blog.51cto.com/u_12907475/5462350
标签:Python,文件,读写,open,函数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
对python中不同模块(函数、类、变量)的调用详解
2022-01-17 14:36:38
Python实现拼接多张图片的方法
2022-07-22 12:58:13
WinHTTP Services 5.1 参考资料
2010-03-27 20:49:00
python发送邮件接收邮件示例分享
2023-05-25 02:01:47
Python Selenium异常处理的实例分析
2021-01-12 17:13:06
BootStrap学习笔记之nav导航栏和面包屑导航
2023-08-16 12:33:22
浅说相册图片详情页面中大图的浏览方式
2009-02-01 18:34:00
![](https://img.aspxhome.com/file/UploadPic/20092/1/12-79.jpg)
Session.TimeOut的最大取值是1440,超出会报错
2011-03-31 11:19:00
解决python中os.system调用exe文件的问题
2023-11-29 14:46:13
![](https://img.aspxhome.com/file/2023/0/63190_0s.png)
js字符串日期yyyy-MM-dd转化为date示例代码
2023-08-06 16:35:58
使用Python的Twisted框架编写非阻塞程序的代码示例
2021-01-22 16:20:51
mysql表的性能提升的相关问题
2010-03-03 16:31:00
python 将对象设置为可迭代的两种实现方法
2023-08-24 18:01:39
python GUI库图形界面开发之PyQt5动态(可拖动控件大小)布局控件QSplitter详细使用方法与实例
2023-06-20 22:10:04
![](https://img.aspxhome.com/file/2023/3/66373_0s.png)
聊聊通过celery_one避免Celery定时任务重复执行的问题
2021-05-20 13:19:12
解决大字段在Form中Post出错的方法
2008-04-17 14:00:00
Python代码注释规范代码实例解析
2023-03-15 04:59:56
python人工智能tensorflow函数tensorboard使用方法
2021-04-21 14:52:46
![](https://img.aspxhome.com/file/2023/7/88887_0s.png)
详解Oracle 中实现数据透视表的几种方法
2023-07-24 03:45:04
python requests使用socks5的例子
2023-09-14 07:06:45