Now I know it's usually not feasible to modify a csv file as you are reading from it so you need to create a new csv file and write to it. The problem I'm having is preserving the original order of the data.
The input csv file looks like follows:
C1 C2 C3
apple BANANA Mango
pear PineApple StRaWbeRRy
I want to turn all the data into lower case and output a new csv file that looks like:
C1 C2 C3
apple banana mango
pear pineapple strawberry
So far I can iterate through the input csv file and turn all the values into lower case but I don't know how to rewrite it back into a csv file in that format. The code I have is:
def clean (input)
aList = []
file = open(input, "r")
reader = csv.reader(file, delimiter = ',')
next(reader, None) # Skip the header but I want to preserve it in the output csv file
for row in reader:
for col in row:
aList.append(col.lower())
So now I have a list with all the lowercase data, how do I rewrite it back into a csv file of the same format (same number of rows and columns) as the input including the header row that I skipped in the code.
csvmodule for this. It's a pity you need to preserve the case of the header line, otherwise you could just process the whole file with thetrprogram (if you're using a Unix-like OS).pd.read_csv(input).apply(str.lower).to_csv(input),as the delimiter, but your sample data uses whitespace. Please explain!