文件
# 1.r和w:只读和只写
# r只读
# w只写,文件已经存在会覆盖写入,不存在则创建文件写入
# 2.rb和wb:只读和只写,非文本的读取和写入
# 3.a追加:在文件末尾增加,文件不存在创建新的文件
# 4.r+,w+,a+
"""
r+:读写,指针在文件开头
w+:读写,文件已经存在会覆盖写入,不存在则创建文件写入
a+:读写,文件存在则在文件末尾追加,文件不存在创建新的文件
"""
1.write和writelines的区别
1.write()传入的是字符串
2.writelines()传入既可以是字符串也可以是字符序列,注意不能是数字序列
2.with函数
可以不用写close()函数
with open("demo.txt", "w", encoding="utf-8") as f:
f.writelines(["你好世界\n", "你好潭州\n", "5"])
with open("demo.txt", "r", encoding="utf-8") as f:
print(f.read())
3.tell()和seek()函数
tell()函数可以告诉你光标所在的位置
seek()可有把光标移动到你想要的位置
__注:因为中文在python的utf—8的编码为3字节,所以当你把光标移动到不是3的倍数是,读出来的数据会报错
4.read()读取文件(从指针所在的位置到文件结束为止),字符串对象
注:line.strip()清除字符串两行的空白字符
with open("static/demo.txt", "r", encoding="utf-8")as f:
file = f.read()
print(file.strip())
print(type(file)) #<class 'list'>
readline():每次出一行内容,所以,读取占用内存小,适合大文件,字符串对象
with open("static/demo.txt", "r", encoding="utf-8")as f:
line = f.readline()
print(type(line)) # <class 'str'>
while line:
print(line.strip())
line = f.readline()
6.readlines():读取整个问价所有行,保存在一个列表里,每行作为一个元素,读取大文件比较占内存
with open("static/demo.txt", "r", encoding="utf-8")as f:
lines = f.readlines()
print(type(lines)) # <class 'list'>
for line in lines:
print(line.strip())
7.with为什么可以实现文件自动打开和关闭呢?—上下文管理器
class RunTime:
def __enter__(self):
print("进来了")
self.start_time = datetime.now()
print(self.start_time)
def __exit__(self, exc_type, exc_val, exc_tb):
self.end_time = datetime.now()
print(self.end_time)
print("出去了")
print("运行时间:{}".format(self.end_time - self.start_time))
run = RunTime()
with run as a: # 上下文管理器
print("我是type")
for i in range(100000):
type("hello")
如果想获取更多有关python的信息,和想玩python制作的小程序,可以关注微信公众号(dreamspy)。我们一起用python改变世界,一起用python创造梦想。


1117

被折叠的 条评论
为什么被折叠?



