打开文件
#方法一:使用系统内置函数open==================================================
def open_file():
try:
file = open(r"test.txt", "r")
print("文件名称:",file.name)
print("文件是否已关闭:",file.closed)
print("文件访问模式:", file.mode)
finally:
file.close()
print("使用close方法,关闭文件状态为:", file.closed)
open_file()
print("======open方法,写入文件======")
def open_write():
try:
f = open("test.txt", "w")
f.write("这是使用open,写入的文件\nhello word\n第三行\n")
finally:
f.close()
open_write()
#方法二:使用with方法======================================================
print("======使用with方法,读取文件======")
def with_read():
with open(r"test.txt", "r") as file:
data = file.readline()
while data:
print(data, end="")
data = file.readline()
with_read()
print("======使用with方法,写入文件======")
def with_write():
with open("test.txt", "w") as f:
f.write("使用with的write方法,写入文件,旧的文件已经被覆盖\n")
with_write()
with_read()
print("======使用with方法追加文件======")
def with_add():
with open("test.txt", "a") as f:
f.write("这是with的追加文件!!!\n")
with_add()
with_read()
print("======使用with方法,迭代读取文件======")
def for_read():
with open("test.txt", "r") as f:
for i in f:
print(i, end="")
for_read()
"""
文件名称: test.txt
文件是否已关闭: False
文件访问模式: r
使用close方法,关闭文件状态为: True
======open方法,写入文件======
======使用with方法,读取文件======
这是使用open,写入的文件
hello word
第三行
======使用with方法,写入文件======
使用with的write方法,写入文件,旧的文件已经被覆盖
======使用with方法追加文件======
使用with的write方法,写入文件,旧的文件已经被覆盖
这是with的追加文件!!!
======使用with方法,迭代读取文件======
使用with的write方法,写入文件,旧的文件已经被覆盖
这是with的追加文件!!!
"""
with的上下文机制原理
class Sample:
def __enter__(self):
#获取资源
print("enter方法")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
#释放资源
print("exit退出")
def do_sth(self):
print("doing something")
if __name__ == '__main__':
with Sample() as s:
s.do_sth()
"""
enter方法
doing something
exit退出
"""
with的上下文,其他实现方式
import contextlib
@contextlib.contextmanager
#使用装饰器,将一个函数变成,上下文管理器
def file(filename):
print("文件正在打开")
yield {}
print("文件的末尾")
with file("hello.txt") as f:
print("文件操作中。。。")
"""
文件正在打开
文件操作中。。。
文件的末尾
"""
随机读取文件
"""
当需要读取的文件位置在文件中间,或者后半半部分,就需要随机读取
"""
name = ("zhangsan","lisa","wangwu")
age = (33,11,22)
def main():
"""写入文件"""
with open("test2.txt","a") as f:
for i in range(len(name)):
content = "{name:<10}{age:>4}\n".format(name=name[i], age=age[i])
f.write(content)
main()
def read():
with open("test2.txt", "r") as f:
f.seek(15) #指定读取开始位置,第一行:0,第三行:30
print("第二行数据:{}, 姓名:{}, 年龄:{}".format(
f.tell(),
f.read(10).strip(),
int(f.read(5))))
read()
#使用yield方式分批读取====================================
name_length = 10
read_length = 5
line_count = 0
def yield_read():
seek_offset = 0
with open("test2.txt", "r") as f:
while True:
f.seek(seek_offset + name_length)
data = f.read(read_length)
if data:
global line_count
line_count += 1
seek_offset = f.tell()
yield int(data) #局部返回
else:
return
num = 0
for i in yield_read():
num += i
print("一共读取了:{}行信息,用户平均年龄为:{}".format(line_count, num / line_count))
"""
第二行数据:15, 姓名:lisa, 年龄:11
一共读取了:3行信息,用户平均年龄为:22.0
"""
文件的编码方式
编码方式有:
#encode编码,decode解码=========
def gbk_demo():
data = "百度一下".encode("GBK") #使用gbk编码
u_data = "百度一下".encode("utf-8") #使用utf-8编码
print("gkb编码:",data)
print("utf-8编码:",u_data)
res_data = data.decode("GBK")
res_udata = u_data.decode("utf-8")
print("使用GBK解码:", res_data)
print("使用utf-8解码:", res_udata)
gbk_demo()
"""
gkb编码: b'\xb0\xd9\xb6\xc8\xd2\xbb\xcf\xc2'
utf-8编码: b'\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b'
使用GBK解码: 百度一下
使用utf-8解码: 百度一下
"""
#使用chardet查询默认编码方式
import chardet
message = "哈哈".encode()
print("查询默认编码方式:",chardet.detect(message))
"""
查询默认编码方式: {'encoding': 'utf-8', 'confidence': 0.7525, 'language': ''}
"""