0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PythonでCSVファイルの各先頭のスペースを全て削除する

Posted at

skipinitialspace=Trueを指定することで先頭の半角スペースだけ削除できます。

import csv

csv_file = open('sample.csv', 'r', encoding='cp932', errors='', newline='')
f = csv.reader(csv_file, delimiter=',', doublequote=True, lineterminator='\r\n', quotechar="'", skipinitialspace=True)
newfile = open('sample_nospaces.csv', 'w', encoding='cp932')
writer = csv.writer(newfile, doublequote=True, lineterminator='\n')
header = next(f)
writer.writerow(header)
for row in f:
    row = row
    writer.writerow(row)
csv_file.close()
sample.csv
id,NO1,NO2,NO3,NO4,NO5
101,1,1,1,1,1
102, a b , a b,1,2 ,1
103, ,,,,
104, , 3,1,1,1
sample_nospaces.csv
id,NO1,NO2,NO3,NO4,NO5
101,1,1,1,1,1
102,a b ,a b,1,2 ,1
103,,,,,
104,,3,1,1,1
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?