trans_methods.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2024/5/16
  3. # @Author : 魏志亮
  4. import os
  5. import re
  6. import warnings
  7. import chardet
  8. import pandas as pd
  9. from utils.log.trans_log import trans_print
  10. warnings.filterwarnings("ignore")
  11. # 获取文件编码
  12. def detect_file_encoding(filename):
  13. # 读取文件的前1000个字节(足够用于大多数编码检测)
  14. with open(filename, 'rb') as f:
  15. rawdata = f.read(1000)
  16. result = chardet.detect(rawdata)
  17. return result['encoding']
  18. # 读取数据到df
  19. def read_file_to_df(file_path, read_cols=list()):
  20. trans_print('开始读取文件', file_path)
  21. df = pd.DataFrame()
  22. encoding = detect_file_encoding(file_path)
  23. if str(file_path).lower().endswith("csv"):
  24. if read_cols:
  25. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols)
  26. else:
  27. df = pd.read_csv(file_path, encoding=encoding)
  28. else:
  29. xls = pd.ExcelFile(file_path)
  30. # 获取所有的sheet名称
  31. sheet_names = xls.sheet_names
  32. for sheet in sheet_names:
  33. if read_cols:
  34. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet, usecols=read_cols)])
  35. else:
  36. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet)])
  37. trans_print('文件读取成功', file_path, '文件数量', df.shape)
  38. return df
  39. def __build_directory_dict(directory_dict, path):
  40. # 遍历目录下的所有项
  41. for item in os.listdir(path):
  42. item_path = os.path.join(path, item)
  43. if os.path.isdir(item_path):
  44. __build_directory_dict(directory_dict, item_path)
  45. elif os.path.isfile(item_path):
  46. if path not in directory_dict:
  47. directory_dict[path] = []
  48. types = ['xls', 'xlsx', 'csv']
  49. if str(item_path).split(".")[-1] in types:
  50. if str(item_path).count("~$") == 0:
  51. directory_dict[path].append(item_path)
  52. # 读取所有文件
  53. # 读取路径下所有的excel文件
  54. def read_excel_files(read_path):
  55. directory_dict = {}
  56. __build_directory_dict(directory_dict, read_path)
  57. return [path for paths in directory_dict.values() for path in paths if path]
  58. # 创建路径
  59. def create_file_path(path, is_file_path=False):
  60. if is_file_path:
  61. path = os.path.dirname(path)
  62. if not os.path.exists(path):
  63. os.makedirs(path)
  64. # 格式化风机名称
  65. def generate_turbine_name(turbine_name='F0001', prefix='F'):
  66. strinfo = re.compile(r"[\D*]")
  67. name = strinfo.sub('', str(turbine_name))
  68. return prefix + str(int(name)).zfill(3)