主要分享一个写入文件的工具类,便于在开发中经常调试写入文件的情况
Python中删除文件时使用:os.remove("文件路径")
,下面的工具类已经包含了这个功能
示例代码
# -*- coding:utf-8 -*-
class FileWriter(object):
def __init__(self, file_path: str, drop_if_exist=False):
"""初始化
:param file_path:文件路径
:param drop_if_exist:如果文件存在,是否需要删除
"""
import os
self.file_path = file_path
if drop_if_exist and os.path.exists(self.file_path):
os.remove(file_path)
def write(self, line, split='\n'): # 写入单条数据
"""写入一个数据"""
with open(self.file_path, 'a') as file:
file.write(str(line) + split)
def write_list(self, line_list: list, mode='a', line_split="\n"): # 写入一个列表
if isinstance(line_list, list):
with open(self.file_path, mode=mode) as file:
for line in line_list:
file.write(str(line) + line_split)
else:
raise TypeError("write object needs type list")
# 只有在当前文件直接执行时,才会执行以下代码
if __name__ == '__main__':
writer = FileWriter("my_file.txt", drop_if_exist=True)
writer.write('hello world')
writer.write('python')
writer.write_list(['hello', 'world'])