1
0

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 5 years have passed since last update.

Python csvの文字列の長さを変える

Posted at

import csv

極値テストの際にcsvの文字列の長さを変更する必要がありました。
EXCELでサクッとやればよかったんですが興味本位でPythonで文字列の長さを変更しました。以下、コード

コード

length.py
import csv
import random

# 出力用リスト
exp_list = []
max_len = 256
# csv読み込み
with open(r'sample.csv', 'r',encoding='utf-8') as f:
    reader = csv.reader(f)
    for r in reader:
        buff = ''
        r_len = len(r[0])
        while len(r) < max_len - r_len:
            ran = random.randrange(10)
            r += str(ran)
        for x in r:
            buff += x
        exp_list.append(buff)
# csv書き込み
with open(r'output.csv', 'w',encoding='utf-8') as f:
    writer = csv.writer(f, lineterminator='\n')
    writer.writerow(exp_list)

実行結果

実行コマンド.txt
python length.py

入力

sample.csv
data1
data2
data3

出力

sample.csv
data198745...
data265644...
data354351...
1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?