Last active
February 20, 2023 15:04
-
-
Save sebastianlujan/ce7df48d51be241e24d61ba1f9e3c797 to your computer and use it in GitHub Desktop.
sort a csv by a condition
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 | |
| def read_csv_file(filename): | |
| with open(filename, 'r') as csvfile: | |
| reader = csv.reader(csvfile) | |
| rows = list(reader) | |
| return rows | |
| # Sort rows by fourth column (Sep 10, 2022) in descending order | |
| # Sort rows with "V" in fourth column to the front | |
| def sort_rows(rows): | |
| rows.sort(key=lambda x: (x[3] != "V", x[3]), reverse=True) | |
| return rows | |
| def write_csv_file(filename, rows): | |
| with open(filename, 'w', newline='') as outfile: | |
| # Create a CSV writer object | |
| writer = csv.writer(outfile) | |
| # Write the sorted rows to the output file | |
| for row in rows: | |
| if row[3] == "V": | |
| writer.writerow(row) | |
| else: | |
| continue | |
| if __name__ == '__main__': | |
| input_filename = 'file.csv' | |
| output_filename = 'output2.csv' | |
| # Read input CSV file | |
| rows = read_csv_file(input_filename) | |
| # Sort rows | |
| sorted_rows = sort_rows(rows) | |
| # Write sorted rows to output CSV file | |
| write_csv_file(output_filename, sorted_rows) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment