Created
February 15, 2024 08:11
-
-
Save AyemunHossain/75b019e314ffdae9b64652877c0b2f0f to your computer and use it in GitHub Desktop.
Shuffle a csv file rows
This file contains 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 | |
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