![](/img/trans.png)
[英]Remove extra commas, space & lines offset in .csv file using python
[英]remove space in csv file with python
我有一個 csv 文件,如:
id ,age ,type ,destination
1,10,20 ,Paris
2,20,50 ,Canada
3,10,23 ,London
在類型和目標值之后,我們有空間。 我想刪除它,我的輸出將是:
1,10,20,paris
2,20,50,canada
3,10,23,london
我怎樣才能通過python做到這一點?
對於這種更快的方法是使用文本編輯器:)
如果你使用 vim
%s/ //g
%s - 應用於整個文件選擇
// - 要替換的字母
// - 代替
g - 全局
或者只是在任何編輯器中使用查找和替換
在 python 假設 file.csv 是你的文件
with open('file.csv','r') as f:
content = f.readlines()
cleaned = ''
for line in content:
if line != '\n':
cleaned += line
print(cleaned.replace(" ",""))
就像是:
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]
我從這里得到了這個答案: Strip white space from CSV file
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]
#Definition for strippping whitespace
def trim(dataset):
trim = lambda x: x.strip() if type(x) is str else x
return dataset.applymap(trim)
然后您現在可以像這樣將 trim(CSV/Excel) 應用於您的代碼(作為循環的一部分等)
dataset = trim(pd.read_csv(dataset))
dataset = trim(pd.read_excel(dataset))
我找到了答案:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.