python第九期学习笔记(三)

#!/usr/bin/python3
#_*_ coding:utf-8 _*_
#author:inwell
#Time:2019/10/15 16:14

# f=open("1_homework.py",mode="r",encoding="utf-8")
# #读取前10个字符
# msg=f.read(10)
# #读取10个字符以后的字符
# msg1=f.read()
# print(msg)
# print(msg1)
# f.close()

# f=open("02 format.py",mode="r",encoding="utf-8")
# readline()一次只读取一行内容
# msg1=f.readline()
# msg2=f.readline()
# msg3=f.readline()
# msg4=f.readline()
# print(msg1)
# print(msg2)
# print(msg3)
# print(msg4)
# f.close()

# f=open("02 format.py",mode="r",encoding="utf-8")
# #readlines()返回一个列表,列表里面每个元素是原文件的每一行,如果文件很大,占内存,容易崩盘
# msg=f.readlines()
# print(msg)

# f=open("02 format.py",mode="r",encoding="utf-8")
# #遍历文件的所有行,并进行输出
# for line in f:
# print(line)

# f=open("t1.txt",mode="w",encoding="utf-8")
# # #在w模式下写入文件
# # #写的时候,如果文件不存在,先创建文件,在写入文件
# # #当文件存在的时候,写入,会覆盖原来文件中的内容,写入新的内容
# # # f.write("随便耍耍")
# # f.write("好嗨哟,感觉人生已经到达了高潮")
# # f.close()

f=open("t1.txt",mode="a",encoding="utf-8")
#在a模式下写入文件是追加的方式
f.write(" 我的小伙伴们都惊呆了")
f.close()

f=open("t1.txt",mode="r+",encoding="utf-8")
#r+读写模式,先读,后写,所以后面写入的内容,不会读取出来
msg=f.readlines()
print(msg)
f.write(" 七月的风,八月的雨,")
f.close()
 
#以读写模式打开文件
# f=open("t1.txt",mode="r+",encoding="utf-8")
#移动到文件开头
# f.seek(0)
# content=f.read()
#输出文件所有内容
# print(content)
# f.seek(0)
# f.seek(0,2)
# content2=f.read()
#没有输出任何内容,因为上面已经读取了全文,文件也没有关闭
# print(content2)
# # f.seek(0)
# # f.write("姚明")
# # f.flush()
# # f.close()

f=open("t1.txt",mode="r+",encoding="utf-8")
f.seek(0)
content=f.read()
print(content)
f.seek(0)
f.seek(0,2)
content2=f.read()
print(content2)
#光标移动到开头
f.seek(0)
f.write("张国荣")
#位置9:一个中文件点3个字节
#tell():告诉我们光标在哪个位置
print(f.tell())
f.close()
 
f=open("t1.txt",mode="r+",encoding="utf-8")
#根据模式,来输出文件的读取,写入状态
print(f.readable())
print(f.writable())

 

原文地址:https://www.cnblogs.com/gaoyuxia/p/11684099.html