2016-05-01 14 views
-1

私はPythonの初心者です。 whileを使用して特定のパスに10個のファイルを作成するファイルを作成するスクリプトを作成する方法を知りたい(最初のファイル名は1.txt2.txt10.txt)。`while 'を使って10個の` .txt`ファイルを作成するにはどうすればいいですか?

+4

ようこそStackOverflow!まずはhttp://stackoverflow.com/help/how-to-askを読んでください。 –

+0

「for」は、なぜか少し論理的な選択肢ですか? – usr2564301

+0

おそらく、それはプログラミングクラスの課題なので、生徒は最初にループを手動で行う方法を学ぶ前に、カウントして状態をチェックする何かがあると教えられます。 –

答えて

1

あなたがループしながら、使用を主張する場合は、解決策は次のようになります。

i = 1 
while i <= 10: 
    with open("{}.txt".format(i), "w") as handle: 
     handle.write("Some content ...") 
    i += 1 

をしかし、forループを使用すると、この場合にははるかに適切です:

for i in range(1, 11): 
    with open("{}.txt".format(i), "w") as handle: 
     handle.write("Some content ...") 
-1
import os 


def create_files(path, n): 
    i = 1 
    while i <= n: 
     with open(os.path.join(path, str(i) + '.txt'), 'w+') as f: 
      f.write('content') 
     i += 1 

if __name__ == '__main__': 
    create_files('/tmp/test', 10) 

whileループ、open(path、 'w +')を使用してファイルを作成します。

私はPythonにも新しく、それが助けて、楽しんでくれることを願っています。

関連する問題