python 文件操作类
Python 2022/6/12 18:01:02 点击:不统计
http://%77w%77%2E%66%6F%72%61%73%70%2E%63n网站制作学习
平时写python 经常用到文件操作,比如读取文件,写入文件,创建文件夹等等,写了一个类方便使用
双线下面是代码,可以直接复制
=========================
"""
@ luhuijie
@ class dir and file
@ 操作文件, 文件夹的类
"""
import os
class file_lib:
"""
初始化内容,
默认获取工作路径
"""
def __init__(self):
self.basepath = os.getcwd()
self.selfpath =os.curdir
pass
"""
获取上一级目录
"""
def parent_path(self,path):
return os.path.abspath(os.path.join(path,".."))
pass
"""
创建文件夹
path 为文件夹路径,递归创建文件夹
"""
def make_dir(self, path):
if ''==path:
return False
try:
path = path.strip()
path = path.rstrip("\\")
# 先判断上一级的存在
ppath = os.path.dirname(path)
is_exist = self.is_exists(ppath)
if not is_exist:
self.make_dir(ppath)
is_exist = self.is_exists(path)
if not is_exist:
os.mkdir(path)
return True
except BaseException as e:
print(e)
return False
pass
"""
读取文件夹
args path, 路径,
deep_flag 是否逐级向下读取
默认 True 逐级读取
False
path_flag 返回相对路径还是绝对路径
默认 True 相对路径
False 绝对路径
return 返回文件夹 对应数组,
"""
def read_dir(self, path, deep_flag=True, path_flag=True):
# file 操作类
result = []
if not self.is_exists(path):
return result
if self.is_file(path):
result.append(path)
return result
templist = os.listdir(path)
for temppath in templist:
tempfilepath = path + "/" + temppath
tempresult = (path_flag and temppath) or tempfilepath
if '.'==temppath or '..'==temppath:
continue
elif self.is_file(tempfilepath):
result.append(tempresult)
elif self.is_dir(tempfilepath):
if deep_flag:
tempresult = self.read_dir(tempfilepath,deep_flag,path_flag)
result.append(tempresult)
else:
result.append(tempresult)
else:
return []
return result
pass
"""
读取文件
args path 文件路径
readtype 读取内容类型,如果是文件夹或者不存在的文件,返回 False
默认 text 默认一次读取文件内容,返回字符串
line 逐行读取,返回数组
code 读取文件 编码格式 默认 utf-8
return 读取文件内容,根据 readtype 返回
"""
def read_file(self,path, readtype = 'text', code='utf-8'):
if self.is_dir(path) or not self.is_file(path):
return False
result = []
with open(path, encoding=code) as fIn:
lines = fIn.readlines()
for line in lines:
result.append(line.strip())
if 'text'==readtype:
return "".join(result)
else:
return result
pass
"""
写文件
args path 文件路径
content 内容
type 写入类型
w 默认 清理后写入(覆盖式的写入)或者叫修改
a 追加写入
返回 True或者false
"""
def write_file(self,path,content,type='w',code='utf-8'):
#获取文件先判断文件夹
parentdir = self.parent_path(path)
if not self.is_dir(parentdir):
self.make_dir(parentdir)
try:
#开始写入文件
bar = open(path, type)
bar.write(content)
bar.close()
return True
except BaseException as e:
print(e)
return False
pass
"""
判断是否是文件,
args path 路径地址 如果不存在则返回false
如果是文件夹 页返回false
"""
def is_file(self,path):
return self.is_exists(path) and os.path.isfile(path)
pass
"""
判断路径是否是文件夹
"""
def is_dir(self,path):
return self.is_exists(path) and os.path.isdir(path)
pass
"""
判断路径是否存在
"""
def is_exists(self,path):
return os.path.exists(path)
pass
http://%77%77%77%2E%66%6F%72%61%73%70%2E%63%6E
·上一篇:python 引入文件 >> ·下一篇:python 时间类 >>