Forráskód Böngészése

change format created file

Alex Sidorov 1 éve
szülő
commit
26c910f972
1 módosított fájl, 28 hozzáadás és 50 törlés
  1. 28 50
      main.py

+ 28 - 50
main.py

@@ -1,6 +1,7 @@
 import csv, os, re, sys, argparse
 from logger import *
 from datetime import datetime
+import pandas as pd
 
 
    
@@ -8,9 +9,7 @@ parse = argparse.ArgumentParser(
     description="Программа для сбора информации из csv файлов")
 parse.add_argument('-p', '--path', help='Указать в какой директории искать',
                    default=os.path.dirname(sys.argv[0]))
-parse.add_argument('-e', '--encoding',
-                   help='Указать в какой кодировке сохранять', default='windows-1251')
-parse.add_argument('-s', '--open_encoding',
+parse.add_argument('-e', '--open_encoding',
                    help='Указать в какой кодировке открывать', default='utf-16')
 args = parse.parse_args()
 
@@ -32,21 +31,8 @@ class ObjectReady:
     def get_len_dict(self) -> int:
         return len(self.__dict__)
 
-    def get_csv_row(self) -> str:
-        if self.get_len_dict() < 11:
-            return ';'.join((self.frame, self.cabinet))
-
-        dic = self.__dict__
-        # print(dic)
-        try:
-            row_interface = ';'.join(
-                [';'.join((dic.get(F"ip{i}"), dic.get(F"mac{i}"))) for i in range(self.count_interface)
-            ])
-
-            return ';'.join((str(dic.get("frame")), str(dic.get("cabinet")), str(dic.get("os")), str(
-                    dic.get("motherboard")), dic.get("cpu"), str(dic.get("ram")), row_interface))+'\n'
-        except AttributeError:
-            return ';'.join((self.frame, self.cabinet))+"\n"
+    def get_row(self) -> str:
+        return self.__dict__
 
 
 def get_paths() -> list:
@@ -62,19 +48,18 @@ def convert_mb_to_gb(val: str) -> str:
     return str(round(numbers/1024, 1))+' GB'
 
 
-def get_ser_motherboard(row: str) -> str:
-    if len(row) > 0:
-        if row[6] not in ['To be filled by O.E.M.', 'Default string']:
-            return row[6]
-        else:
-            return None
-    else:
-        return None
+def get_ser_motherboard(row: list) -> str:
+    try:
+        return row if row not in ['To be filled by O.E.M.', 'Default string'] else None
+    except IndexError:
+        pass
 
 
 def get_data_from_file(path: str, obj: ObjectReady) -> None:
     global COUNT_INTERFACE
+    
     with open(path, 'r', encoding=args.open_encoding) as file:
+        
         cs = csv.reader(file, delimiter=',')
 
         next(cs)
@@ -82,18 +67,18 @@ def get_data_from_file(path: str, obj: ObjectReady) -> None:
         obj.os = line_info_computers[7]
         obj.cpu = line_info_computers[13]
         obj.ram = convert_mb_to_gb(line_info_computers[14])
-
-        obj.ip1 = None
-        obj.mac1 = None
-
+        obj.motherboard = None
+        obj.count_interface = 0
         count_interface = 0
-        for x in cs:
-            if x[0] == '6200':
-                obj.motherboard = get_ser_motherboard(x)
-
-            if x[0] == '2600' and len(x) > 2 and check_correct_controller(x[3]):
-                setattr(obj, F'ip{count_interface}', x[6].split(' ')[0])
-                setattr(obj, F'mac{count_interface}', x[-3])
+        
+        for line in cs:
+            data = list(pd.Series(line))
+            if data[0] == '6200':
+                obj.motherboard = get_ser_motherboard(data[6])
+
+            if data[0] == '2600' and len(data) > 2 and check_correct_controller(data[3]):
+                setattr(obj, F'ip{count_interface+1}', data[6].split(' ')[0])
+                setattr(obj, F'mac{count_interface+1}', data[-3])
                 count_interface += 1
 
         # Увеличиваем значение если количестов интерфейсов больше в этой строке
@@ -107,7 +92,7 @@ def get_data_from_file(path: str, obj: ObjectReady) -> None:
 def get_ready_information() -> list[ObjectReady]:
     list_objects = []
     for path in get_paths():
-
+        
         obj = ObjectReady()
         obj.frame = os.path.basename(os.path.dirname(path))
         obj.cabinet = re.findall(
@@ -127,18 +112,11 @@ def get_ready_information() -> list[ObjectReady]:
 
 
 def create_csv(list_obj: list[ObjectReady]) -> None:
-    namefile = F"result-{datetime.today().strftime('%Y-%m-%d-%H.%M.%S')}"
-
-    with open(F"{namefile}.csv", 'w', newline='', encoding=args.encoding) as f:
-        header_csv = F"frame;cabinet;os;motherboard;cpu;ram{''.join([F';ip{i+1};mac{i+1}' for  i in range(COUNT_INTERFACE)])}\n"
-        f.write(header_csv)
-
-        for obj in list_obj:
-            row = obj.get_csv_row()
-            logger.info(row)
-            f.write(obj.get_csv_row())
-            
-
+    namefile = F"result-{datetime.today().strftime('%Y-%m-%d-%H.%M.%S')}.xlsx"
+    data = [row.get_row() for row in list_obj]
+    df = pd.DataFrame(data=data)
+    df.to_excel(namefile, index= False)
+    
 if __name__ == '__main__':
     create_logger()