2017-02-04 3 views
-1

から特定の行の末尾に特定の文字列を追加しますので、今私が持っている:ファイル

私は、ファイルに書き込み、それを作るためにパイソンを使用するにはどうすればよい
1,A 
2,B 
3,C 

1,A,some_string1 
2,B,some_string2 
3,C,some_string3 

すべてのI

1,A,abc 
2,B,abc 
3,C,abc 

使用:このようなすべての行に同じ文字列を追加するための解決策を見つけた

file_name = "thing" 
string_to_add = "abc" 

with open('thing', 'r') as f: 
    file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()] 

with open('thing', 'w') as f: 
    f.writelines(file_lines) 
+0

一定の長さですか? – schwobaseggl

+0

これは何でも構いません – Yaya

答えて

1

あなたは、任意のサイズのファイルで、このようにそれを行うことができます。

import random 

    with open('input.csv') as in_file: 
     with open('out.csv', 'w') as out_file: 
      for in_line in in_file: 
       in_line = in_line.strip() 
       rand_line = random.randint(1,100) # your random string 
       out_file.write("{},{}\n".format(in_line, rand_line)) 
+0

2つの異なるファイルを開く理由を説明できますか? – Yaya

+0

ファイルを変更する簡単な解決策はありません。 –

0

csvstringrandomは、あなたが探しているツールです:ランダムな文字列がありましたら

import csv 
import string 
import random 

with open('input.csv') as fin: 
    with open('output.csv', 'w') as fout: 
    writer = csv.writer(fout) 
    for row in csv.reader(fin): 
     # random string of length 6 consisting of any upper/lower case ascii letters 
     rand_str = ''.join(random.choice(string.lowercase) for x in range(6)) 
     writer.writerow(row + [rand_str]) 
+0

申し訳ありませんが、私はランダムなモジュールを介して生成された文字列を意味する文字列を意味random_stringと言ったとき、適切に説明していない。 – Yaya

関連する問題