2016-10-06 12 views
-2

私は多くの人がpythonファイルのIOパターンに慣れていると確信しています。複数のファイルに書き込む

outfile = open("myFile", "w") 
data.dump() 
outfile.close() 

私たちはすでにファイルを持っており、これにアクセスできます。今、もう少し複雑なものを作りたいと思っています。

私は、整数iを反復するforループを持っているとします。範囲が1〜1000であり、スペースや頭痛を救うためにデータを書きたいのですが、私は%100 == 0となる度にループに保存しています。

for i in range (1, 1001): 
    #scrape data from API and store in some structure 
    ... 
    if i % 100 == 0: 
     #Create a new outfile, open it, and write the data to it 
     ?... 

どうすればPythonで自動的に固有の名前の新しいファイルを作成し、データを書き込むためにファイルを開いたり閉じたりしますか?

+3

あなたは何をする必要があるかを説明します。あなたは何を理解できないでしょうか? –

答えて

1
>>> my_list = [] 
>>> for i in range(1, 1001): 
...  # do something with the data... in this case, simply appending i to a list 
...  my_list.append(i) 
...  if i % 100 == 0: 
...   # create a new file name... it's that easy! 
...   file = fname + str(i) + ".txt" 
...   # create the new file with "w+" as open it 
...   with open(file, "w+") as f: 
...    for item in my_list: 
...     # write each element in my_list to file 
...     f.write("%s" % str(item)) 
...   print(file) 
... 
file100.txt 
file200.txt 
file300.txt 
file400.txt 
file500.txt 
file600.txt 
file700.txt 
file800.txt 
file900.txt 
file1000.txt 

空白を入力しますが、単純な文字列連結ではこのトリックを行います。

関連する問題