Python的文件操作

发表于 2020-06-03 13:49:57
阅读 29

介绍

介绍

今天我们来学习如何使用 python 操作文件

教程

文件读取操作

读取一行

通过readline()方法读取一行内容

fo = open("haha.txt", "r")
line = fo.readline()
print (line)
fo.close()

读取全部内容

通过readlines()方法去掉全部内容到数组里

fo = open("haha.txt", "r")
str = fo.readlines()
print (str)
fo.close()

读取指定长度

通过read(n)方法读取n个字符内容

fo = open("haha.txt", "r")
chars = fo.read(4)
print (chars)
fo.close()

定位读取

通过seek()方法移动游标,读取指定位置开始的内容

fo = open("haha.txt", "r")
fo.seek(5)
chars = fo.read(2)
print (chars)
fo.close()

文件写入操作

追加写入

这里的模式是 a,表示 append,追加写入就是在文件已有内容的后面写入新内容的模式

fo = open("haha.txt", "a")
fo.write("this is new line\n")
fo.close()

重置写入

这里的模式是 w,表示 write,重置写入就是抛弃文件已有内容重新写入新内容的模式

fo = open("haha.txt", "w")
fo.write("this is new line\n")
fo.close()

定位写入

这里的模式是 r+,表示 read plus,通过seek()方法移动游标,在指定位置开始写入新内容

fo = open("haha.txt", "r+")
fo.seek(5)
fo.write(" the world")
fo.close()

总结

  • r模式,用来读内容

  • w模式,用来写内容

  • a模式,用来追加内容

  • r+模式,用来编辑内容,可读,可写