簡體   English   中英

用python刪除csv文件中的空間

[英]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

  1. 你可以試試這個代碼
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. 或者您可以使用 Pandas 讀取 CSV(或 Excel 文件)並使用此自定義函數對其進行修剪,如下所示
#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM