Python 设计一个工具类
Python中的工具类通常包含一些常用的函数或方法,可以在多个模块中重复使用。下面是一个示例工具类,其中包含一些常用的文件处理和字符串处理函数:
import os
class Utils:
@staticmethod
def read_file(file_path):
with open(file_path, "r") as f:
return f.read()
@staticmethod
def write_file(file_path, content):
with open(file_path, "w") as f:
f.write(content)
@staticmethod
def file_exists(file_path):
return os.path.exists(file_path)
@staticmethod
def is_file(file_path):
return os.path.isfile(file_path)
@staticmethod
def is_dir(dir_path):
return os.path.isdir(dir_path)
@staticmethod
def get_files_in_dir(dir_path):
if not Utils.is_dir(dir_path):
raise ValueError(f"{dir_path} is not a directory")
return [os.path.join(dir_path, f) for f in os.listdir(dir_path) if Utils.is_file(os.path.join(dir_path, f))]
@staticmethod
def is_palindrome(s):
return s == s[::-1]
上述示例工具类包含以下功能:
read_file(file_path):读取文件内容。
write_file(file_path, content):将内容写入文件。
file_exists(file_path):检查文件是否存在。
is_file(file_path):检查给定路径是否为文件。
is_dir(dir_path):检查给定路径是否为目录。
get_files_in_dir(dir_path):获取给定目录中的所有文件。
is_palindrome(s):检查给定字符串是否为回文。
上述示例仅供参考,实际工具类应根据具体需求定义常用的函数和方法。