Skip to content

Instantly share code, notes, and snippets.

@AyemunHossain
Created February 15, 2024 08:11
Show Gist options
  • Save AyemunHossain/75b019e314ffdae9b64652877c0b2f0f to your computer and use it in GitHub Desktop.
Save AyemunHossain/75b019e314ffdae9b64652877c0b2f0f to your computer and use it in GitHub Desktop.
Shuffle a csv file rows
import csv
import random
def clean_csv(input_file, output_file):
# Open the input CSV file for reading
with open(input_file, 'r', newline='') as csvfile:
reader = csv.reader(csvfile)
# Read all rows except the header
rows = list(reader)[1:]
# Shuffle the rows
random.shuffle(rows)
# Open the output CSV file for writing
with open(output_file, 'w', newline='') as outfile:
writer = csv.writer(outfile)
# Write the header row to the output file
writer.writerow(next(csv.reader(open(input_file))))
# Write the shuffled rows to the output file
writer.writerows(rows)
# Input and output file paths
input_file = 'input.csv'
output_file = 'output.csv'
# Call the function to clean the CSV file
clean_csv(input_file, output_file)
print("CSV file cleaned successfully!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment