Test Python code: Shape file to FracPaQ

Published:

code

import shapefile
import sys

# --- Configuration ---
# 1. Change this to the path of your input shapefile
input_shapefile = "PCA1_Vertical_Outcrop.shp" 
# 2. Change this to the name of your desired output file
output_txtfile = "coordinates.txt"
# ---------------------

try:
    # Open the output text file in 'write' mode
    with open(output_txtfile, 'w') as f:
        
        # Open the shapefile using the shapefile.Reader
        with shapefile.Reader(input_shapefile) as sf:
            
            print(f"Reading {sf.numRecords} features from {input_shapefile}...")
            
            # Loop through each shape (feature) in the shapefile
            for shape in sf.shapes():
                
                # 'shape.parts' lists the starting index for each part.
                # If it's a simple LineString, parts = [0]
                # If it's a MultiLineString, parts = [0, 15, 30] (e.g.)
                # We add the total number of points as the final 'end' index
                parts = list(shape.parts) + [len(shape.points)]

                # Iterate through each *part* of the shape
                # In a simple LineString, this loop runs once.
                # In a MultiLineString, it runs for each line.
                for i in range(len(parts) - 1):
                    start_index = parts[i]
                    end_index = parts[i+1] # Index *after* the last point
                    
                    # Get all the points for this specific part
                    part_points = shape.points[start_index:end_index]
                    
                    # A line must have at least 2 points (4 numbers)
                    if len(part_points) < 2:
                        continue # Skip this part (e.g., a single point)
                    
                    # Create a flat list to hold all coordinates
                    # e.g., [x1, y1, x2, y2, x3, y3]
                    flat_coords = []
                    for point in part_points:
                        flat_coords.append(str(point[0])) # X
                        flat_coords.append(str(point[1])) # Y
                    
                    # Join all coordinates with a tab (\t)
                    # and add a newline (\n) at the end
                    output_line = "\t".join(flat_coords)
                    f.write(output_line + "\n")

    print(f"✅ Successfully exported all line features to {output_txtfile}")

except FileNotFoundError:
    print(f"Error: The file '{input_shapefile}' was not found.")
    sys.exit(1)
except shapefile.ShapefileException as e:
    print(f"Error reading shapefile: {e}")
    sys.exit(1)
except Exception as e:
    print(f"An unexpected error occurred: {e}")
    sys.exit(1)