今天写的是导出的csv文件,在数据爬取的时候方便我们检查
下面开始我们的代码操作
import csv
from datetime import datetime
import os
import pandas
class ItemFileMixIn:
# 带OS开头的,说明是用python,os包拼接的文件路径,不存在操作系统不兼容的问题
ROOT_DIR = root_path = os.path.abspath(os.path.dirname(__file__)).rstrip('utils') + 'file/'
# 一般文件目录
config = ROOT_DIR + 'file/'
"""
导出到 csv 的工具类
@param head_keys: Array item_file的表头
例 :['com_name', 'project_name']
@param head_keys_CN: Array 最终打开时 将表头字段名替换为中文必须和 head_keys 一一对应
例:['公司名', '项目名']
@param item_file: False 是否开启导出至 csv 文件的功能 默认为 False 不导出
@param csv_file_name: String 导出的文件名 由程序指定
@param auto_open_file: True 写入完成后是否自动打开
@param item_file_deduplication: True 是否最终去重,由程序指定,
"""
head_keys = None
head_keys_CN = None
item_file = False # 是否不入库直接生成csv文件,便于爬取数据的检查
_csv_file_name = None
auto_open_file = True
def _write_file_head(self, file_path=config, file_name='item'):
isExists = os.path.exists(file_path)
if not isExists:
raise FileNotFoundError('文件储存位置未找到')
# 以创建时间命名文件名 防止文件创建时产生冲突
self._csv_file_name = file_path + file_name + datetime.now().strftime('%m-%d-%H-%M-%S') + '.csv'
try:
if self.head_keys:
with open(self._csv_file_name, 'w', newline='') as vf:
csv_write = csv.writer(vf)
csv_write.writerow(self.head_keys_CN)
print("\033[1;36m{}\033[0m".format(self._csv_file_name + ' 完成创建'))
else:
raise TypeError("请指定head_keys字段,类型为list")
except PermissionError:
raise FileExistsError('请先关闭文件 ' + self._csv_file_name + ' !!!')
def _auto_open(self):
print('\n' + self._csv_file_name + '\n')
if getattr(self, 'item_file_deduplication', True):
# 默认数据去重, 若有一行不规则则不去重,勿改,类中指定
# 在简体中文环境下,EXCEL打开的CSV文件默认是ANSI编码 所以默认编码为简体中文环境即GBK
data = pandas.read_csv(self._csv_file_name, encoding='GBK', decimal='~')
data.drop_duplicates(subset=None, keep='first', inplace=True) # 数据去重
data.to_csv(self._csv_file_name, encoding='GBK', index=False)
if self.auto_open_file:
os.startfile(self._csv_file_name)
def write_item(self, item, *args, **kwargs):
if self._csv_file_name:
with open(self._csv_file_name, 'a+', newline='', errors='ignore') as vf:
csv_write = csv.writer(vf)
if self.head_keys:
row = [item.get(key, '') for key in self.head_keys]
if args:
row += args
setattr(self, 'item_file_deduplication', False)
csv_write.writerow(row)
else:
raise ValueError('item未指定写入字段')
一般文件目录都是提前写好了,所以到时候直接引入就行,在file_path=‘文件目录’
然后你可以在你写的类里面直接继承就行了,帮到你的话记得点赞关注