今天我们来学习如何使用 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+模式,用来编辑内容,可读,可写