python3.7入门系列十一 文件读写
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python3.7入门系列十一 文件读写,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1591字,纯文字阅读大概需要3分钟。
内容图文
![python3.7入门系列十一 文件读写](/upload/InfoBanner/zyjiaocheng/829/991079be97de4795aca3ec7749180762.jpg)
打开文件 open() 函数
常用格式 open(file, mode='r') https://docs.python.org/3/library/functions.html 这里有所有python内建的函数及描述文档
f = open("d:/1.txt", 'w')
f.write("hello python")
f.close()
上面的代码以w(写)的方式打开文件d:/1.txt,然后写入 hello python, 最后关闭文件。运行程序后,找到d:/1.txt文件并打开,发现里面的内容是 hello python, 说明程序运行成功
f = open('d:/1.txt', 'r')
msg = f.read()
f.close()
print(msg)
运行结果:
hello python
以 r (只读)方式打开文件,然后读取文件内容,再输出文件内容,即输出前面写入的 hello python
打开文件写入多行内容
f = open("d:/2.txt", 'r')
lines = f.readlines()
f.close()
print(type(lines))
for line in lines:
print(line.strip())
运行程序,显示结果:
<class 'list'>
hello python1
hello python2
hello python3
hello python4
hello python5
hello python6
hello python7
hello python8
hello python9
hello python10
可见readlines()方法返回一个list对象
f = open("d:/2.txt", 'r')
line = f.readline()
while line:
print(line.strip())
line = f.readline()
f.close()
运行程序,显示结果:
hello python1
hello python2
hello python3
hello python4
hello python5
hello python6
hello python7
hello python8
hello python9
hello python10
readline()方法一次只读取一行,read()方法返回文件全部内容,readlines()方法以列表的形式返回文件全部内容
f = open("d:/2.txt", 'a')
f.write('这行是追加的')
f.close()
以 a 方式打开文件,写入的内容将追加到最后。运行上面的代码发现确实追加了内容到最后
关键字with 在不再需要访问文件后将其关闭, python会保证with代码段内的文件对象自动关闭
with open("d:/3.txt", 'w') as f:
f.write('写入文件的内容')
本文内容到此结束,更多内容可关注公众号和个人微信号:
内容总结
以上是互联网集市为您收集整理的python3.7入门系列十一 文件读写全部内容,希望文章能够帮你解决python3.7入门系列十一 文件读写所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。