# Import the os and re modules | |
import os | |
import re | |
# Define the directory where the csv files are located | |
directory = "." | |
# Define a function to remove invalid characters from a csv file | |
def remove_invalid_chars(file): | |
# Open the file in read mode with UTF-8 encoding and ignore errors | |
with open(file, "r", encoding="utf-8", errors="ignore") as infile: | |
# Read the file content as a string | |
content = infile.read() | |
# Remove any null bytes from the string | |
content = content.replace("\x00", "") | |
# Remove any non-printable characters from the string | |
# content = re.sub(r"[^\x20-\x7E]", "", content) | |
# Open the file in write mode with UTF-8 encoding | |
with open(file, "w", encoding="utf-8") as outfile: | |
# Write the modified content to the file | |
outfile.write(content) | |
# Loop through each file in the directory | |
for file in os.listdir(directory): | |
# Check if the file is a csv file | |
if file.endswith(".csv"): | |
# Remove invalid characters from the csv file and print the result | |
print(f"Removing invalid characters from {file}...") | |
remove_invalid_chars(os.path.join(directory, file)) | |
print(f"{file} is cleaned.") | |