-2

I have a csv file like:

id ,age ,type ,destination
1,10,20     ,Paris
   
2,20,50      ,Canada
3,10,23     ,London

After type and destination values we have space. I want to remove it and my out put will be:

1,10,20,paris   
2,20,50,canada
3,10,23,london

How can I do it by python?

mojgan
  • 19
  • 7

4 Answers4

1

For this quicker way is to use a text editor :)

If you use vim

%s/ //g

%s - apply to whole file selection

/ / - letter to substitute

// - substitute

g - globally

or simply use find and replace in any editor

In python assuming file.csv is your file

with open('file.csv','r') as f:
    content = f.readlines()
    cleaned = ''
    for line in content:
        if line != '\n':
            cleaned += line
    print(cleaned.replace(" ",""))
Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40
0

Something like:

with open(filename, 'r') as f:
    reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
    return [[x.strip() for x in row] for row in reader]

I took this answer from here: Strip white spaces from CSV file

vojta
  • 122
  • 1
  • 15
0
  1. You can Try this code
import csv

aList=[]
with open(self.filename, 'r') as f:
    reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
    return [[x.strip() for x in row] for row in reader]
  1. Or you can Read a CSV (or Excel file) using Pandas and trim it using this custom function as follows
#Definition for strippping whitespace
def trim(dataset):
    trim = lambda x: x.strip() if type(x) is str else x
    return dataset.applymap(trim)

And then You can now apply trim(CSV/Excel) to your code like so (as part of a loop, etc.)

dataset = trim(pd.read_csv(dataset))
dataset = trim(pd.read_excel(dataset))
Aamir Shah
  • 31
  • 7
0

I found the answer:

text = open("file.csv", "r", encoding="utf8")
        text = ''.join([i for i in text]) \
            .replace("  ", "")
        x = open("file1" + i + ".csv", "w", encoding="utf8")
        x.writelines(text)
        x.close()
mojgan
  • 19
  • 7