To create a Python script that reduces the number of rows in a CSV file to the last 25% of the logs while preserving the headers, follow these steps:
Approach
- Count Total Rows: First, determine the total number of rows in the CSV file, including the header.
- Calculate Data Rows: Subtract one from the total rows to get the number of data rows (excluding the header).
- Determine Rows to Keep: Compute 25% of the data rows using ceiling to ensure at least the closest integer value.
- Process the File: Read the file again, write the header first, then skip the initial rows to retain only the last 25% of the data rows.
Solution Code
import csv
import math
def main():
input_file = 'input.csv'
output_file = 'output.csv'
# Count total lines in the input file
with open(input_file, 'r') as f:
total_lines = sum(1 for line in f)
if total_lines < 1:
print("The input file is empty.")
return
data_lines = total_lines - 1 # Subtract header row
if data_lines <= 0:
# If there are no data rows, just copy the header
with open(input_file, 'r') as f_in, open(output_file, 'w', newline='') as f_out:
writer = csv.writer(f_out)
writer.writerows(csv.reader(f_in))
return
# Calculate the number of data rows to keep (25% rounded up)
K = math.ceil(data_lines * 0.25)
skip = data_lines - K # Number of data rows to skip
# Process the file to write the header and the last K data rows
with open(input_file, 'r') as f_in, open(output_file, 'w', newline='') as f_out:
reader = csv.reader(f_in)
writer = csv.writer(f_out)
# Write the header
header = next(reader)
writer.writerow(header)
# Skip the first 'skip' data rows
for _ in range(skip):
next(reader, None) # Use None to avoid StopIteration if needed
# Write the remaining rows (the last K data rows)
for row in reader:
writer.writerow(row)
if __name__ == '__main__':
main()
Explanation
- Counting Rows: The script first reads the input file to count all rows, including the header.
- Header Handling: The header is written first to ensure it is preserved.
- Data Calculation: The number of data rows to keep is calculated as 25% of the total data rows, using
math.ceil to round up to ensure at least the closest integer value.
- Skipping Rows: The script skips the initial rows to retain only the last 25% of the data rows, ensuring the output file contains the header followed by the desired data subset.
This approach efficiently processes the file in two passes, ensuring minimal memory usage even for large files. The use of math.ceil ensures that at least 25% of the data rows are retained, rounded up to the nearest whole number.