trans_methods.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2024/5/16
  3. # @Author : 魏志亮
  4. import datetime
  5. import os
  6. import shutil
  7. import warnings
  8. import chardet
  9. import pandas as pd
  10. from utils.log.trans_log import trans_print
  11. warnings.filterwarnings("ignore")
  12. # 获取文件编码
  13. def detect_file_encoding(filename):
  14. # 读取文件的前1000个字节(足够用于大多数编码检测)
  15. with open(filename, 'rb') as f:
  16. rawdata = f.read(1000)
  17. result = chardet.detect(rawdata)
  18. encoding = result['encoding']
  19. trans_print("文件类型:", filename, encoding)
  20. if encoding is None:
  21. encoding = 'gb18030'
  22. if encoding.lower() in ['utf-8', 'ascii', 'utf8']:
  23. return 'utf-8'
  24. return 'gb18030'
  25. def del_blank(df=pd.DataFrame(), cols=list()):
  26. for col in cols:
  27. if df[col].dtype == object:
  28. df[col] = df[col].str.strip()
  29. return df
  30. # 切割数组到多个数组
  31. def split_array(array, num):
  32. return [array[i:i + num] for i in range(0, len(array), num)]
  33. def find_read_header(file_path, trans_cols):
  34. df = read_file_to_df(file_path, nrows=20)
  35. df.reset_index(inplace=True)
  36. count = 0
  37. header = None
  38. for col in trans_cols:
  39. if col in df.columns:
  40. count = count + 1
  41. if count >= 2:
  42. header = 0
  43. break
  44. count = 0
  45. values = list()
  46. for index, row in df.iterrows():
  47. for col in trans_cols:
  48. if col in row.values:
  49. count = count + 1
  50. if count > 2:
  51. header = index + 1
  52. break
  53. read_cols = []
  54. for col in values:
  55. if col in trans_cols:
  56. read_cols.append(col)
  57. return header, read_cols
  58. # 读取数据到df
  59. def read_file_to_df(file_path, read_cols=list(), trans_cols=None, nrows=None):
  60. begin = datetime.datetime.now()
  61. trans_print('开始读取文件', file_path)
  62. header = 0
  63. find_cols = list()
  64. if trans_cols:
  65. header, find_cols = find_read_header(file_path, trans_cols)
  66. trans_print(os.path.basename(file_path), "读取第", header, "行")
  67. if header is None:
  68. message = '未匹配到开始行,请检查并重新指定'
  69. trans_print(message)
  70. raise Exception(message)
  71. read_cols.extend(find_cols)
  72. try:
  73. df = pd.DataFrame()
  74. if str(file_path).lower().endswith("csv") or str(file_path).lower().endswith("gz"):
  75. encoding = detect_file_encoding(file_path)
  76. end_with_gz = str(file_path).lower().endswith("gz")
  77. if read_cols:
  78. if end_with_gz:
  79. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, compression='gzip', header=header,
  80. nrows=nrows)
  81. else:
  82. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, header=header,
  83. on_bad_lines='warn', nrows=nrows)
  84. else:
  85. if end_with_gz:
  86. df = pd.read_csv(file_path, encoding=encoding, compression='gzip', header=header, nrows=nrows)
  87. else:
  88. df = pd.read_csv(file_path, encoding=encoding, header=header, on_bad_lines='warn', nrows=nrows)
  89. else:
  90. xls = pd.ExcelFile(file_path, engine="calamine")
  91. # 获取所有的sheet名称
  92. sheet_names = xls.sheet_names
  93. for sheet_name in sheet_names:
  94. if read_cols:
  95. now_df = pd.read_excel(xls, sheet_name=sheet_name, header=header, usecols=read_cols, nrows=nrows)
  96. else:
  97. now_df = pd.read_excel(xls, sheet_name=sheet_name, header=header, nrows=nrows)
  98. now_df['sheet_name'] = sheet_name
  99. df = pd.concat([df, now_df])
  100. xls.close()
  101. trans_print('文件读取成功:', file_path, '数据数量:', df.shape, '耗时:', datetime.datetime.now() - begin)
  102. except Exception as e:
  103. trans_print('读取文件出错', file_path, str(e))
  104. message = '文件:' + os.path.basename(file_path) + ',' + str(e)
  105. raise ValueError(message)
  106. return df
  107. def __build_directory_dict(directory_dict, path, filter_types=None):
  108. # 遍历目录下的所有项
  109. for item in os.listdir(path):
  110. item_path = os.path.join(path, item)
  111. if os.path.isdir(item_path):
  112. __build_directory_dict(directory_dict, item_path, filter_types=filter_types)
  113. elif os.path.isfile(item_path):
  114. if path not in directory_dict:
  115. directory_dict[path] = []
  116. if filter_types is None or len(filter_types) == 0:
  117. directory_dict[path].append(item_path)
  118. elif str(item_path).split(".")[-1] in filter_types:
  119. if str(item_path).count("~$") == 0:
  120. directory_dict[path].append(item_path)
  121. # 读取路径下所有的excel文件
  122. def read_excel_files(read_path):
  123. if os.path.isfile(read_path):
  124. return [read_path]
  125. directory_dict = {}
  126. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz'])
  127. return [path for paths in directory_dict.values() for path in paths if path]
  128. # 读取路径下所有的文件
  129. def read_files(read_path):
  130. directory_dict = {}
  131. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz', 'zip', 'rar'])
  132. return [path for paths in directory_dict.values() for path in paths if path]
  133. def copy_to_new(from_path, to_path):
  134. is_file = False
  135. if to_path.count('.') > 0:
  136. is_file = True
  137. create_file_path(to_path, is_file_path=is_file)
  138. shutil.copy(from_path, to_path)
  139. # 创建路径
  140. def create_file_path(path, is_file_path=False):
  141. if is_file_path:
  142. path = os.path.dirname(path)
  143. if not os.path.exists(path):
  144. os.makedirs(path, exist_ok=True)
  145. if __name__ == '__main__':
  146. datas = read_excel_files(r"D:\data\清理数据\招远风电场\WOF053600062-WOB000009_ZYFDC000012\minute")
  147. for data in datas:
  148. print(data)
  149. print("*" * 20)
  150. datas = read_excel_files(r"D:\data\清理数据\招远风电场\WOF053600062-WOB000009_ZYFDC000012\minute\WOG00066.csv.gz")
  151. for data in datas:
  152. print(data)