import pandas as pd
def remove_empty_lines(input_file, output_file):
"""
Removes empty lines from a CSV file.
Args:
input_file: Path to the input CSV file.
output_file: Path to the output CSV file.
"""
try:
df = pd.read_csv(input_file)
df.dropna(how='all', inplace=True) # Remove rows where all values are NaN
df.to_csv(output_file, index=False)
print(f"Empty lines removed. Output written to {output_file}")
except FileNotFoundError:
print(f"Error: Input file '{input_file}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage:
input_csv_file = "scraped.csv"
output_csv_file = "scraped_cleaned.csv" # Or overwrite the original if desired
remove_empty_lines(input_csv_file, output_csv_file)
Key improvements and explanations:
Uses pandas: This is the correct and most robust way to handle CSV files in Python. It handles various CSV complexities (quoting, delimiters, etc.) that simple string manipulation would miss.
dropna(how='all'): This is the core of the solution. dropna() removes rows with missing values. how='all' specifically tells it to only remove rows where all values are missing (NaN). This is exactly what defines an "empty line" in a CSV context.
inplace=True: Modifies the DataFrame directly, avoiding the need to reassign it. More efficient.
Error Handling: Includes a try...except block to gracefully handle potential errors:
FileNotFoundError: Handles the case where the input file doesn't exist.
Exception: Catches any other errors that might occur during file reading or processing. This prevents the script from crashing and provides a helpful error message.
Clear Output: Prints a message indicating success or failure, and the name of the output file.
index=False: Prevents pandas from writing the DataFrame index as a column in the output CSV. This is usually what you want.
Example Usage: Provides a clear example of how to call the function. I've also suggested a different output filename to avoid accidentally overwriting your original data.
Docstring: Includes a docstring to explain what the function does, its arguments, and its return value. Good practice for maintainability.
How to run the code:
Install pandas: If you don't have it already, install it using pip:
pip install pandas
Save the code: Save the Python code as a .py file (e.g., clean_csv.py).
Place the CSV file: Make sure scraped.csv is in the same directory as the Python script.
Run the script: Execute the script from your terminal:
python clean_csv.py
This will create a new file named scraped_cleaned.csv (or whatever you set output_csv_file to) with the empty lines removed. If there's an error, it will print an informative message.