Python txt文件常用读写操作代码实例
作者:不放弃自己 时间:2021-08-22 04:38:28
python读取txt文件
#方式一:
file = r'D:\test.txt'
with open(file, 'rb+') as f: #可读可写二进制,文件若不存在就创建
data = f.readlines() #读取文本所有内容,并且以数列的格式返回结果,一般配合for in使用
print(data)
#方式二:
file = r'D:\test.txt'
f = open(file,"rb+") #可读可写二进制,文件若不存在就创建
data = f.readlines()
print(data)
f.close() #关闭文件
python写入txt文件
#方式一:
file = r'D:\test.txt'
f = open(file,"wb+") #可读可写二进制,文件若不存在就创建
str='kfjlhgfj光'
f.write(str.encode())
f.close() #关闭文件
#方式二:
file = r'D:\test.txt'
with open(file,"ab+") as f: #可追加可写二进制,文件若不存在就创建
str='kfjlhgfj光'
f.write(str.encode())
读写模式
关于open()的读写模式:
'r':读
'w':写
'a':追加
'r+' == r+w(可读可写,文件若不存在就报错(IOError))
'w+' == w+r(可读可写,文件若不存在就创建)
'a+' ==a+r(可追加可写,文件若不存在就创建)
对应的,如果是二进制文件,就都加一个b就好啦:
'rb''wb''ab''rb+''wb+''ab+'
注意:open和with open的区别
使用open方法,文件操作完毕之后必须手动关闭,否则长期保持对文件的连接状态,造成内存溢出的现象发生。
使用with open会自动化关闭文件
来源:https://www.cnblogs.com/hghua/p/13396077.html
标签:Python,txt,文件,读写
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
关于golang 字符串 int uint int64 uint64 互转问题
2023-07-13 17:52:44
教你用python将数据写入Excel文件中
2021-12-29 03:28:38
![](https://img.aspxhome.com/file/2023/8/97638_0s.png)
使用SQL语句 INNER JOIN 联接表
2008-04-27 20:31:00
![](https://img.aspxhome.com/file/UploadPic/20084/27/sql_15s.gif)
用图片做网站输入验证的构想
2009-02-02 10:18:00
![](https://img.aspxhome.com/file/UploadPic/20092/2/pics1-65.jpg)
停止事件冒泡和阻止浏览器默认行为的脚本
2008-09-09 22:09:00
ASP 获取腾讯IP地址的代码
2011-02-26 11:19:00
python方差检验的含义及用法
2022-08-09 15:53:56
Python回调函数用法实例详解
2021-04-10 14:31:15
服务器XMLHTTP(Server XMLHTTP in ASP)基础
2008-11-11 12:45:00
微信小程序实现图片上传功能
2023-09-06 13:08:44
python自动化实现登录获取图片验证码功能
2022-09-21 13:23:59
![](https://img.aspxhome.com/file/2023/1/82711_0s.jpg)
pytorch超详细安装教程之Anaconda、PyTorch和PyCharm全套安装流程
2023-12-23 15:27:50
![](https://img.aspxhome.com/file/2023/5/97375_0s.jpg)
JavaScript table的排序类
2008-10-06 12:56:00
Python学习之迭代器详解
2022-09-02 12:45:45
![](https://img.aspxhome.com/file/2023/7/95567_0s.jpg)
Python进阶学习修改闭包内使用的外部变量
2023-04-09 01:23:04
![](https://img.aspxhome.com/file/2023/1/112931_0s.png)
PHP中的traits实现代码复用使用实例
2023-11-22 04:27:55
python进阶教程之模块(module)介绍
2021-06-16 12:52:07
利用canvas实现的加载动画效果实例代码
2023-06-29 22:49:51
![](https://img.aspxhome.com/file/2023/1/55891_0s.gif)
colab中修改python版本的全过程
2022-10-31 07:18:38
![](https://img.aspxhome.com/file/2023/9/81609_0s.png)
c++生成dll使用python调用dll的方法
2023-02-16 11:40:05