LoginSignup
3
3

More than 5 years have passed since last update.

【Python】リストの要素を使ってさしこみ文書の作成

Last updated at Posted at 2018-07-09

コードはPython2.6と3.6での動作を確認しました。
コメントで @shiracamus さんがより簡潔で有用な記述を指摘してくださっている。

やりたいこと

list.py
 Name = [anago,ikura,unko]

みたいなリストから

Text0.txt
 Hello, I am anago
Text1.txt
 Hello, I am ikura
Text2.txt
 Hello, I am unko

っていう感じのファイルを作りたい。

やってみた

say_hi.py
Name = ["Anago","Ikura","Unko"]
for i in range(3):
        with open("Text{0}.txt".format(i),"w") as file:
                file.write("Hello, I am {0}".format(Name[i]))


作ったテキストファイルは以下のとおり

Text0.txt
 Hello, I am anago
Text1.txt
 Hello, I am ikura
Text2.txt
 Hello, I am unko

Forによる繰り返しと、with open みたいなコマンドと ”bunshou”.formatみたいなのを組み合わせたらできました。

参考にさせていただいたサイト

ファイル読み書き file open read write

pythonでファイルの読み書き

python for文を初心者向けに解説!for文基礎はこれで完璧

【Python入門】format関数で文字列の書き方

すこし複雑な例

eat_sushi.py
number = [1,2,1000]
name = ["anago","ikura","unko"]
for i in range(3):
        for j in range(3):
                with open("eatsushi{0}{1}.txt".format(i,j),"w") as file:
                        file.write("Hello, I am {0} \n ".format(name[j]))
                        file.write("\n\n")
                        file.write("I have eaten {0} sushis  \n".format(number[i]))
                        file.write("Good bye"+"{0}{1}".format(name[j],number[i]))
                        file.write("\n\n")


同じディレクトリに

eatsushi00.tet
Hello, I am anago 


I have eaten 1 sushis  
Good byeanago1

などが生成される。

3
3
4

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
3
3