Created
June 30, 2025 10:52
-
-
Save kewgis/4091700e49cd86078191e29d9c82dd86 to your computer and use it in GitHub Desktop.
Re-order the values in the x,y and z columns of a text file (e.g. a bathymetry .pts/.xyz file) such that they conform to a true .xyz format readable by GDAL and openable in QGIS.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
""" | |
This script re-orders the values in the x,y and z columns of a text file (e.g. a bathymetry .pts/.xyz file) such that they conform to a true .xyz format readable by GDAL and openable in QGIS. | |
In many cases the data in an "xyz" file falls foul of the GDAL requirement that: | |
“Cells with same Y coordinates must be placed on consecutive lines. For a same Y coordinate value, the lines in the dataset must be organized by increasing X values.” | |
https://gdal.org/en/stable/drivers/raster/xyz.html | |
""" | |
# Define a function to reorder the file | |
def reorder_file(input_file, output_file): | |
with open(input_file, 'r') as file: | |
# reader = csv.reader(file, delimiter='\t') # Read the tab-separated file | |
reader = csv.reader(file, delimiter=' ') # Read the space-separated file | |
data = list(reader) # Convert the file content to a list | |
# Sort the data by the second column, then the first column | |
data.sort(key=lambda row: (row[1], row[0])) | |
# Write the sorted data to a new file | |
with open(output_file, 'w', newline='') as file: | |
writer = csv.writer(file, delimiter='\t') # Use tab as the delimiter | |
writer.writerows(data) | |
# Example usage | |
input_file = 'Bathymetry_1x1m.pts' # Replace with your input file name | |
output_file = 'Bathymetry_1x1m_re-sorted.xyz' # Replace with your desired output file name | |
reorder_file(input_file, output_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment