import csv Opening the CSV file with open('staffdir.csv') as file: Creating a CSV reader…
- User
import csv
Opening the CSV file
with open('staff_dir.csv') as file: # Creating a CSV reader object reader = csv.reader(file)
Reading the CSV data into a list of rows
sd = list ('staff_dir.csv')
Delete the spaces and replace single space
sd = [[cell.strip().replace(" ", " ") for cell in row] for row in sd]
Set the title for the data
header = [cell.upper() for cell in sd[0]] sd[0] = header for i in range(1, len(sd)): sd[i][0] = sd[i][0].upper() sd[i][-1] = sd[i][-1].title() sd[i][2] = sd[i][2].lower() sd[10][-1] = 'Location'
Checking for duplications in the data
duplicates = [row for i, row in enumerate(sd) if row in sd[:i]]
if duplicates: print(" Duplicated rows found at row numbers:") else: print(" no duplicated rows found")
Removing duplicate rows
sd = [row for i, row in enumerate(sd) if row not in sd[:i]]
'staff_dir.csv'
please help me to correct it
- Assistant
Sure! I noticed a few issues in your code. Here's the corrected code:
import csv # Opening the CSV file with open('staff_dir.csv') as file: # Creating a CSV reader object reader = csv.reader(file) # Reading the CSV data into a list of rows sd = list(reader) # Delete the spaces and replace multiple spaces with a single space sd = [[cell.strip().replace(" ", " ") for cell in row] for row in sd] # Set the title for the data header = [cell.upper() for cell in sd[0]] sd[0] = header for i in range(1, len(sd)): sd[i][0] = sd[i][0].upper() sd[i][-1] = sd[i][-1].title() sd[i][2] = sd[i][2].lower() sd[0][-1] = 'Location' # Checking for duplications in the data duplicates = [row for i, row in enumerate(sd) if row in sd[:i]] if duplicates: print("Duplicated rows found at row numbers:") for row in duplicates: print(sd.index(row)) else: print("No duplicated rows found") # Removing duplicate rows sd = list(set(tuple(row) for row in sd)) sd = [list(row) for row in sd] # Writing the updated data back to the CSV file with open('staff_dir.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(sd)