基础部分:文件操作
python# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: 1_getline
# Description: 题目:有1个json格式的文件file.txt大小约为10k
# Author: zhaoyaowei
# Date: 2023/3/11 15:25
# -------------------------------------------------------------------------------
import os
from mmap import mmap
def get_lines():
"""
初级:读取整个文件的数据
:return:
"""
with open("file.txt", "r") as f:
return f.readlines()
def get_lines_optimize():
"""
进阶:比如待处理文件大小为10G,但内存只有4G,如何优化
理解yield:使用yield的函数被称作生成器函数(generator function).
生成器方法:next()--执行下一步、send()--可传入值,再执行下一步
对比return:
1. return直接返回结果,程序终止运行,并销毁局部变量
2. yield会产生1个断点,暂停挂起函数,并且返回某个值,返回后不再继续往下运行
3. 有yield的函数返回1个可迭代的生成器generator对象,并不会执行函数代码,直至对其调用next()
可以使用for循环(自动调用next())、或者调用next()、send()方法
:return:
"""
a = []
with open("file.txt", "r") as f:
data = f.readlines(60000)
a.append(data)
yield a
def get_lines_super(filepath):
"""
高级:进阶方法资源消耗和性能不友好,可继续优化,采用mmap模块
mmap:一种虚拟内存映射文件方法。fileno-文件描述符号;length=0,映射整个文件。mmap操作字节,不是字符串。
:return:
"""
with open(filepath, 'r+') as f:
m = mmap(f.fileno(), 0)
index = 0
for i, char in enumerate(m):
if char == b'\n':
yield m[index:i+1].decode()
index = i + 1
def process(line):
print(f"处理数据:{line}")
if __name__ == '__main__':
# 读取整个文件的数据,并处理
for e in get_lines():
process(e)
# 大文件分批优化处理,采用yield
for e in get_lines_optimize():
process(e)
# 高级处理, mmap
fp = os.getcwd() + '/file.txt'
for e in get_lines_super(fp):
process(e)
python# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: 2_获取文件夹的层级文件夹和文件
# Description:
# Author: zhaoyaowei
# Date: 2023/3/12 13:39
# -------------------------------------------------------------------------------
import os
def get_directory_content(spath):
"""
:param spath: 文件夹路径
:return: 该文件夹中文件的路径以及其包含文件夹中文件的路径
"""
# listdir返回path指定的文件夹包含的文件或文件夹的名字的列表
for s_child in os.listdir(spath):
# 路径拼接文件路径
s_child_path = os.path.join(spath, s_child)
# 判断子文件格式是否为文件夹,是,则递归;否则,打印文件路径
if os.path.isdir(s_child_path):
get_directory_content(s_child_path)
else:
print(s_child_path)
if __name__ == '__main__':
spath = "/Users/zhaoyaowei/Desktop/project/InterviewQuestions/Python基础"
get_directory_content(spath)
本文作者:赵耀伟
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!