python中读写都是通过open函数完成的
这是open方法源码中的参数选项
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
通常选择三个就可以了
file:文件的路径
mode: 读,写,创建文件等操作都对应了一个选项字符,通常选读(‘r')或者写('w')就可以了
(mode='a' 是在文件末尾追加内容,可以留意一下)
读文件有按字节读取,按一行读取,按多行读取3种方式encoding:编码格式
f1=open("data/students.txt",mode='r',encoding='utf8')
print(f1.read(10))
print(f1.readline())
print(f1.readline())
print(f1.readlines())
f1.close();
最后一个readlines()是将所有行的数据都读完了
我们这里都是通过一个open的对象read数据,所以上面读过的,下面的就不会再去读一遍了
写数据,这个文件的目录如果不存在,他会帮我们自动创建出来
写的方式就2种,写一行,写多行,注意写完一行数据就换行
写多行的时候,使用的是列表接收 , 看下源码,确实参数只能是列表才行
@abstractmethod
def writelines(self, lines: List[AnyStr]) -> None:
pass
f2=open("data/newdoc.txt",mode='w',encoding='utf8')
f2.write("123456\n")
f2.write("hello world\n")
f2.writelines(["hello java\n","hello python\n","hello linux"])
f2.close();
mode='a',是在已经存在的文件内容末尾追加数据,mode='a+'是如果文件不存在会自动创建,如果存在就是和前面一样在文件末尾追加新的内容
f2=open("data/newdoc.txt",mode='a',encoding='utf8')
f2.write("123456\n")
f2.write("hello world\n")
f2.writelines(["hello java\n","hello python\n","hello linux"])
上面都是用完需要关闭连接,也有可以不用关闭的方法 with open()
with open("data/students.txt", mode="r", encoding='utf8') as f3:
with open("data/newStu2.txt", mode='a', encoding='utf8') as f4:
f4.writelines(f3.readlines())