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?
CodePudding user response:
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(" ",""))
CodePudding user response:
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
CodePudding user response:
- 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]
- 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))