import os import psycopg2 def parse_meta_data(lines): """Extract meta information from the file lines.""" meta = {} for line in lines: line = line.strip() if "NAME" in line: meta['name'] = line.split('=')[-1].strip().replace(')', '').strip() elif "D" in line: meta['d'] = float(line.split('=')[-1].strip().replace(')', '')) elif "R" in line: meta['r'] = float(line.split('=')[-1].strip().replace(')', '')) elif "STOCK" in line: meta['stock'] = float(line.split('=')[-1].strip().replace(')', '')) elif "X MINMAX" in line: parts = line.split('=')[1].strip().split("X")[1:] meta['x_min'] = float(parts[0].strip()) meta['x_max'] = float(parts[1].strip().replace(')', '')) elif "Y MINMAX" in line: parts = line.split('=')[1].strip().split("Y")[1:] meta['y_min'] = float(parts[0].strip()) meta['y_max'] = float(parts[1].strip().replace(')', '')) elif "Z MINMAX" in line: parts = line.split('=')[1].strip().split("Z")[1:] meta['z_min'] = float(parts[0].strip()) meta['z_max'] = float(parts[1].strip().replace(')', '')) return meta def upload_to_postgresql(directory, db_config): """Upload data from files in the directory to PostgreSQL.""" conn = psycopg2.connect(**db_config) cur = conn.cursor() for filename in os.listdir(directory): if filename.endswith(".csv"): with open(os.path.join(directory, filename), 'r') as f: lines = f.readlines() meta_data = parse_meta_data(lines) cur.execute(""" INSERT INTO WELDING_INFO_META (name, d, r, stock, x_min, x_max, y_min, y_max, z_min, z_max) VALUES (%(name)s, %(d)s, %(r)s, %(stock)s, %(x_min)s, %(x_max)s, %(y_min)s, %(y_max)s, %(z_min)s, %(z_max)s) RETURNING id """, meta_data) file_meta_id = cur.fetchone()[0] for order, line in enumerate(lines[10:]): if line.startswith('X,Y,Z'): # Adjust based on actual line format continue x, y, z, g, m, s, f = map(float, line.split(',')) cur.execute(""" INSERT INTO WELDING_INFO (file_meta_id, operation_order, x, y, z, g, m, s, f) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) """, (file_meta_id, order, x, y, z, g, m, s, f)) conn.commit() cur.close() conn.close() if __name__ == "__main__": directory = input("Enter the directory path containing the files: ") db_config = { 'dbname': 'welding', 'user': 'postgres', 'password': 'ts4430!@', 'host': 'localhost', # e.g., 'localhost' 'port': '5432', # e.g., '5432' } upload_to_postgresql(directory, db_config)