Python-10-文件读写_for循环


读文件

当我们在工作中需要从文件中获取内容的时候,我们可以使用Python的内置方法open来完成。

第一步:打开文件

f = open('info.txt')
print(f)

Python-10-文件读写_打开文件_02我们可以看到,默认的文件打开模式为'r',即只读。

直接open会返回一个文件对象。

获取文件对象内容

f = open('info.txt')
for i in f:
print(i)

Python-10-文件读写_for循环_03通过上面的结果,我们可以知道,文件对象是一个可迭代的对象,通过for循环,我们就可以拿到其内容。

更优雅的读取方式read

f = open('info.txt')
res = f.read(100)
print(res)

read(count),我们传入100,代表我们想要读取100个字节。

Python-10-文件读写_打开文件_04

更优雅的读取方式readline

f = open('info.txt')
res = f.readline()
print(res)

Python-10-文件读写_python测试_05如上可知,readline每次只读取一行内容。

注意:readline在读取一行后,文件句柄会停留在上次读取的位置,即通过多次readline可实现顺序读取。

readlines

当我们需要快速的读取全部内容的时候,我们需要使用readlines

f = open('info.txt')
res = f.readlines()
print(res)

Python-10-文件读写_for循环_06如上,readlines返回一个列表对象,我们可以通过遍历列表即可读取每一行的内容。

写文件

普通写

我们已经知道默认的open是r模式,所以写文件就需要我们在打开文件的时候指定w模式,如果需要读权限,则要使用w+模式。

f = open('info.txt',mode='w+')
f.write('hello,python测试和开发!')
res = f.readlines()
print(res)

Python-10-文件读写_for循环_07为什么读取到的内容是空的呢?因为写入的内容还在内存中,当你进行文件关闭的时候才会写入文件。

f = open('info.txt',mode='w+')
f.write('hello,python测试和开发!')
f.close()
s = open('info.txt')
res = s.readlines()
print(res)

Python-10-文件读写_打开文件_08

追加写

f = open('info.txt',mode='w+')
f.write('hello,python测试和开发!')
f.close()
s = open('info.txt',mode='w+')
s.write('ok')
s.close()

m = open('info.txt')
res = m.readlines()
print(res)

Python-10-文件读写_python测试_09

注意:当我们以w+模式打开文件的时候,默认会清空文件。如果需要追加内容到文件,则需要采用a模式。

f = open('info.txt',mode='w+')
f.write('hello,python测试和开发!')
f.close()
s = open('info.txt',mode='a')
s.write('ok')
s.close()

m = open('info.txt')
res = m.readlines()
print(res)

Python-10-文件读写_for循环_10如上,已经解决。

优雅的读写

以上面的操作,我们都需要打开,读写,再关闭,有没有一种方式可以不用这么麻烦呢?

with关键字

其内部实现了__enter__和__exit__方法,我们可以直接使用with实现优雅的文件打开关闭处理。

with open('info.txt',mode='w+') as f:
f.write('hello,python测试和开发!')

Python-10-文件读写_for循环_11怎么样,是不是很优雅!

附录

几种打开文件模式的区别

Python-10-文件读写_python测试_12

几种文件对象的属性

Python-10-文件读写_打开文件_13

所有的文件打开模式

Python-10-文件读写_python测试_14