对于文件来说我们常用的就是读写操作了,首选就是我们的with…open…as方法,进行文件的读写操作,因为这个方法不需要自己进行文件的关闭,由python机制进行自动处理,比较方便也减少我们出现问题的概率
login.txt的内容如下:
abc bcd ef
cdef
读取的文件默认使用为r(read)模式
with open(r'login.txt') as f:#打印读取的内容的类型print (type(f.read()))#打印文件的内容print (f.read())
with open(r'login.txt') as f:#打印读取的内容的类型print (type(f.readlines()))#打印文件的内容print (f.readlines())
ps:read读取的内容为字符串,readlines以换行为分割,读取出的内容为列表
with open(r'login.txt',mode="w") as f:
#写入单行,类型必须为str
print (type(f.write("abcd")))
#打印文件的内容
print (f.write("abcd"))
with open(r'login.txt',mode="w") as f:
#写入单行,类型必须为str
print (type(f.writelines("abcd")))
#打印文件的内容
print (f.writelines("abcd"))
with open(r'login.txt',mode="a") as f:
#写入单行,类型必须为str
print (type(f.write("abcd")))
#打印文件的内容
print (f.write("abcd"))
with open(r'login.txt',mode="a") as f:
#写入单行,类型必须为str
print (type(f.writelines(["abcd\n","sfe"])))
#打印文件的内容
print (f.writelines(["abcd\n","sfe"]))
ps:视频材料大家可以看查看我的bilibili1内容我会持续更新
https://space.bilibili.com/432730836 ↩︎