Akshay Jain
Akshay Jain

Reputation: 21

delimit csv and strip whitespaces to generate new csv

I have a csv file content. Here the delimiter is | i want to remove spaces from the lines. I tried delimiting the files by | and strip each element of space however when writing it to a new csv the space get introduced back.Trying all this in python

| 1497/1 | ACERNO-1 | 1 | 99000010119101 | RUCOPY :Database tree copy | LEGACY_DATA | 283 | OFDB_IT_SIEP |

import csv
aList=[]
workingdir = r"C:\Users\Akshay.Jain\Desktop\CAREER CONNECT"
csvfile = workingdir+r"\01_Wells.csv"
out = csv.writer(open("myfile.csv","w",newline=''),delimiter=',')

with open(csvfile, 'r') as f:
    reader = csv.reader(f, skipinitialspace=True,delimiter='|', quoting=csv.QUOTE_NONE)
    for row in reader:
        for elements in row:

            elements.strip()
            aList.append(row)

        out.writerow(row)

Upvotes: 2

Views: 897

Answers (2)

Manuel
Manuel

Reputation: 706

import csv
aList=[]
workingdir = r"C:\Users\Akshay.Jain\Desktop\CAREER CONNECT"
csvfile = workingdir+r"\01_Wells.csv"
out = csv.writer(open("myfile.csv","w",newline=''),delimiter=',')

with open(csvfile, 'r') as f:
    reader = csv.reader(f, skipinitialspace=True,delimiter='|', quoting=csv.QUOTE_NONE)
    for row in reader:
        for elements in row:

            elements.strip()
            aList.append(elements[:-1])  # Add element by element, removing last item.

        out.writerow(aList[1: -1])  # Write list without first or last item, they are ","

Output:

1497/1,ACERNO-1,1,99000010119101,RUCOPY :Database tree copy,LEGACY_DATA,283,OFDB_IT_SIEP

Upvotes: 0

piripiri
piripiri

Reputation: 2015

Your line

 out.writerow(row)

writes the original row again. Try something like

 out.writerow(aList)

(with creation of aList moved into the loop and with adding elements to aList) or modify row directly, as pointed out by @mgilson in the comments:

for row in reader:
    row = [x.strip() for x in row]
    out.writerow(row)

Upvotes: 1

Related Questions