|
| 1 | +import pandas as pd |
| 2 | +import json |
| 3 | +import os |
| 4 | +from glob import glob |
| 5 | + |
| 6 | +def get_line_ending(file_path): |
| 7 | + with open(file_path, 'rb') as f: |
| 8 | + first_line = f.readline() |
| 9 | + if b'\r\n' in first_line: |
| 10 | + return '\r\n' |
| 11 | + elif b'\r' in first_line: |
| 12 | + return '\r' |
| 13 | + else: |
| 14 | + return '\n' |
| 15 | + |
| 16 | +def sort_csv_files(directives_file): |
| 17 | + with open(directives_file, 'r') as f: |
| 18 | + directives = json.load(f) |
| 19 | + |
| 20 | + for directive in directives: |
| 21 | + files = directive['files'] |
| 22 | + sort_columns = directive['sort_columns'] |
| 23 | + sort_orders = directive.get('sort_orders', [True] * len(sort_columns)) |
| 24 | + |
| 25 | + for file_pattern in files: |
| 26 | + for file_path in glob(file_pattern): |
| 27 | + line_ending = get_line_ending(file_path) |
| 28 | + df = pd.read_csv(file_path) |
| 29 | + |
| 30 | + # Convert column indexes to names if specified as numbers |
| 31 | + columns = df.columns |
| 32 | + sort_columns_actual = [ |
| 33 | + columns[col] if isinstance(col, int) else col |
| 34 | + for col in sort_columns |
| 35 | + ] |
| 36 | + |
| 37 | + sorted_df = df.sort_values(by=sort_columns_actual, ascending=sort_orders) |
| 38 | + |
| 39 | + # Write the sorted DataFrame to a temporary file with the specified line ending |
| 40 | + temp_file_path = file_path + '.tmp' |
| 41 | + sorted_df.to_csv(temp_file_path, index=False) |
| 42 | + |
| 43 | + # Replace original file with the temporary file using the correct line endings |
| 44 | + with open(temp_file_path, 'r', newline='\n') as temp_file: |
| 45 | + with open(file_path, 'w', newline='') as original_file: |
| 46 | + for line in temp_file: |
| 47 | + original_file.write(line.rstrip('\n') + line_ending) |
| 48 | + |
| 49 | + os.remove(temp_file_path) |
| 50 | + |
| 51 | + # sorted_df.to_csv(file_path, index=False, line_terminator=line_ending) |
| 52 | + |
| 53 | +# Example usage |
| 54 | +if __name__ == "__main__": |
| 55 | + sort_csv_files('sort_directives.json') |
0 commit comments