python3.7入门系列十一 文件读写

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bowei026/article/details/90139732

打开文件 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('写入文件的内容')

本文内容到此结束,更多内容可关注公众号和个人微信号:

猜你喜欢

转载自blog.csdn.net/bowei026/article/details/90139732
今日推荐