大唐玉湖-箱变.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 9 16:28:48 2024
  4. @author: Administrator
  5. """
  6. from datetime import datetime
  7. from os import *
  8. import chardet
  9. import pandas as pd
  10. # 获取文件编码
  11. def detect_file_encoding(filename):
  12. # 读取文件的前1000个字节(足够用于大多数编码检测)
  13. with open(filename, 'rb') as f:
  14. rawdata = f.read(1000)
  15. result = chardet.detect(rawdata)
  16. encoding = result['encoding']
  17. if encoding is None:
  18. encoding = 'gb18030'
  19. if encoding and encoding.lower() == 'gb2312' or encoding.lower().startswith("windows"):
  20. encoding = 'gb18030'
  21. return encoding
  22. # 读取数据到df
  23. def read_file_to_df(file_path, read_cols=list(), header=0):
  24. df = pd.DataFrame()
  25. if str(file_path).lower().endswith("csv") or str(file_path).lower().endswith("gz"):
  26. encoding = detect_file_encoding(file_path)
  27. end_with_gz = str(file_path).lower().endswith("gz")
  28. if read_cols:
  29. if end_with_gz:
  30. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, compression='gzip', header=header)
  31. else:
  32. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, header=header, on_bad_lines='warn')
  33. else:
  34. if end_with_gz:
  35. df = pd.read_csv(file_path, encoding=encoding, compression='gzip', header=header)
  36. else:
  37. df = pd.read_csv(file_path, encoding=encoding, header=header, on_bad_lines='warn')
  38. else:
  39. xls = pd.ExcelFile(file_path)
  40. # 获取所有的sheet名称
  41. sheet_names = xls.sheet_names
  42. for sheet in sheet_names:
  43. if read_cols:
  44. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet, header=header, usecols=read_cols)])
  45. else:
  46. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet, header=header)])
  47. return df
  48. def __build_directory_dict(directory_dict, path, filter_types=None):
  49. # 遍历目录下的所有项
  50. for item in listdir(path):
  51. item_path = path.join(path, item)
  52. if path.isdir(item_path):
  53. __build_directory_dict(directory_dict, item_path, filter_types=filter_types)
  54. elif path.isfile(item_path):
  55. if path not in directory_dict:
  56. directory_dict[path] = []
  57. if filter_types is None or len(filter_types) == 0:
  58. directory_dict[path].append(item_path)
  59. elif str(item_path).split(".")[-1] in filter_types:
  60. if str(item_path).count("~$") == 0:
  61. directory_dict[path].append(item_path)
  62. # 读取所有文件
  63. # 读取路径下所有的excel文件
  64. def read_excel_files(read_path):
  65. directory_dict = {}
  66. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz'])
  67. return [path for paths in directory_dict.values() for path in paths if path]
  68. # 创建路径
  69. def create_file_path(path, is_file_path=False):
  70. if is_file_path:
  71. path = path.dirname(path)
  72. if not path.exists(path):
  73. makedirs(path, exist_ok=True)
  74. def read_and_save_csv(file_path):
  75. begin = datetime.now()
  76. base_name = path.basename(file_path)
  77. print('开始', base_name)
  78. df1 = read_file_to_df(file_path + "箱变(1-8号逆变器)数据1.xls")
  79. del df1['Unnamed: 0']
  80. df1['时间'] = pd.to_datetime(df1['时间'])
  81. df1.set_index(keys='时间', inplace=True)
  82. df2 = read_file_to_df(file_path + "箱变(9-16号逆变器)数据1.xls")
  83. del df2['Unnamed: 0']
  84. df2['时间'] = pd.to_datetime(df2['时间'])
  85. df2.set_index(keys='时间', inplace=True)
  86. df3 = read_file_to_df(file_path + "箱变(1-8号逆变器)数据2.xls")
  87. del df3['Unnamed: 0']
  88. df3['时间'] = pd.to_datetime(df3['时间'])
  89. df3.set_index(keys='时间', inplace=True)
  90. df4 = read_file_to_df(file_path + "箱变(9-16号逆变器)数据2.xls")
  91. del df4['Unnamed: 0']
  92. df4['时间'] = pd.to_datetime(df4['时间'])
  93. df4.set_index(keys='时间', inplace=True)
  94. df = pd.concat([df1, df2, df3, df4], axis=1)
  95. df.reset_index(inplace=True)
  96. columns = list(df.columns)
  97. columns.sort()
  98. print(df.columns)
  99. df = df[columns]
  100. df.sort_values(by='时间', inplace=True)
  101. df.to_csv(path.join(r'D:\trans_data\大唐玉湖性能分析离线分析', '05整理数据', base_name + '_箱变.csv'), encoding='utf-8',
  102. index=False)
  103. print('结束', base_name, '耗时:' + str(datetime.now() - begin))
  104. if __name__ == '__main__':
  105. path = r'D:\trans_data\大唐玉湖性能分析离线分析\test'
  106. all_files = read_excel_files(path)
  107. all_paths = set()
  108. for file in all_files:
  109. base_name = path.basename(file).split("箱变")[0]
  110. base_path = path.dirname(file)
  111. if base_name not in all_paths:
  112. all_paths.add(path.join(base_path, base_name))
  113. all_datas = list(all_paths)
  114. all_datas.sort()
  115. print(all_datas)
  116. # with Pool(1) as pool:
  117. # pool.starmap(read_and_save_csv, [(i,) for i in all_datas])