You can achieve this by using Python's built-in csv module to read through your CSV files and check for empty cells. When an empty cell is detected in a file, we'll move that file to a specified folder. To do this, you also need to use the os module for file operations (like moving files) and shutil for high-level file operations like copying or moving.
Here's a step-by-step guide:
-
Read through each CSV file in your directory: Use a for loop to go through each file.
-
Check each cell in the CSV file: Open the file, read its contents, and check each cell in each row. If a cell is empty, flag the file.
-
Move flagged files to another folder: For files with empty cells, move them to a specified folder.
Here's example code to accomplish this. Be sure to replace 'your_directory_here' with the path to your directory containing the CSV files and 'your_destination_directory_here' with the destination directory path.
import csv
import os
import shutil
source_directory = 'your_directory_here'
destination_directory = 'your_destination_directory_here'
# Make sure the destination directory exists, create if it does not
os.makedirs(destination_directory, exist_ok=True)
# Loop through each file in the source directory
for filename in os.listdir(source_directory):
# Construct the full path to your file
file_path = os.path.join(source_directory, filename)
# Check if it's a CSV file
if filename.endswith('.csv'):
move_file = False
with open(file_path, mode='r', encoding='utf-8', newline='') as file:
reader = csv.reader(file)
# Check each row in the CSV
for row in reader:
if any(cell == '' for cell in row): # Check if any cell in the row is empty
move_file = True
break # No need to check further, one empty cell is enough
# Move file if an empty cell was found
if move_file:
destination_file_path = os.path.join(destination_directory, filename)
shutil.move(file_path, destination_file_path)
print(f'Moved "{filename}" to "{destination_directory}"')
print("Processing complete.")
Make sure you have a backup of your files before running scripts that move or modify files to prevent data loss.
This code snippet moves any CSV files with at least one empty cell to the specified destination directory. It doesn't delete any files from the original folder unless they're successfully moved. This script can be extended or modified according to specific requirements, such as handling nested directories or filtering files more precisely.