I have a date column in a CSV file which I am trying to format from dd/mm/yyyy to ddmmyyyy. Some of the days and months are single digit which leave them as dmyyyy. When I run a print statement all of the rows output correctly.
import csv with open(r'input file path,'r') as csvfile: with open(r'outputfilepath,'w') as output: w = csv.writer(output) r = csv.reader(csvfile) for row in r: #this takes care of incomplete rows at the end if len(row[6])>1: dt = row[6].split("/") n = 0 for n in range(len(dt)): if len(dt[n])<2: dt[n] = '0'+dt[n] else: dt[n] row[6] = dt[0]+dt[1]+dt[2] print(row) else: break Print Output:
['a', '', 'Tom', 'Smith', 'J ', '', '12201956'] ['b', '', 'Rick ', 'JOHNSON ', ' ', '', '08121922'] ['c', '', 'Morty', 'Harvey', ' ', '', '06031940'] When I change the print to write rows:
import csv with open(r'input file path,'r') as csvfile: with open(r'outputfilepath,'w') as output: w = csv.writer(output) r = csv.reader(csvfile) for row in r: #this takes care of incomplete rows at the end if len(row[6])>1: dt = row[6].split("/") n = 0 for n in range(len(dt)): if len(dt[n])<2: dt[n] = '0'+dt[n] else: dt[n] row[6] = dt[0]+dt[1]+dt[2] w.writerows(row) else: break I get the output below. I've tried moving the writerows function around with no luck. Looking at the CSV module documentation it should delimit on the commas. I'm relatively new to python. 
w.writerows(row)tow.writerow(row). Plural vs singular. You would also be well-served to be addingnewline=''to youropen()because thecsvwriter does its own newline handling. That would explain the extra newlines in your already messed up data.row[6] = datetime.datetime.strptime(row[6],'%m/%d/%Y').strftime('%m%d%Y')row[6].replace('/', '')? Don't need toimport datetime1/11/2018or12/1/2017. That can be handled with string methods, but it can be handled entirely mindlessly with datetime methods. It takes a bit more thought to write''.join(x.zfill(2) for x in row[6].split('/')). More importantly though is it's clear to the reader what the datetime method is doing.