0
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 1 year has passed since last update.

pythonでひとつ前のtxtファイルのデータを読み取ってlistの次の要素をtxtファイルに出力してくれるプログラム

Last updated at Posted at 2021-11-27

#前回

前回こういうものを作りました

#今回やること
今回は前回のプログラムを少し変えて
ひとつ前のtxtファイルのデータを読み取って
listの次の要素をtxtファイルに出力してくれるプログラムをつくります

#例えば
letter.txtの中に「あ」とだけ書かれていて
このプログラムを実行すると
50音順で次の「い」がletter.txtに上書きされる
というものです

#テキストファイルを読み込む
以下のサイトを参考にしました

まずコードをのせます

f = open('letter.txt') 
letter = f.read()  
f.close()

これをすることによって,letter.txtの文字を読み取って
letterの中に文字列として入れてくれます

#50音の何番目なのかを知る
以下のサイトを参考にしました

japanese_list = ["あ","い","う","え","お",\
         "か","き","く","け","こ",\
         "さ","し","す","せ","そ",\
         "た","ち","つ","て","と",\
         "な","に","ぬ","ね","の",\
         "は","ひ","ふ","へ","ほ",\
         "ま","み","む","め","も",\
         "や","ゆ","よ",\
         "ら","り","る","れ","ろ",\
         "わ","を","ん"]

number = japanese_list.index(letter)
number = number + 1
letter = japanese_list[number]

もしletter.txtに「き」という文字が入っていた場合
indexメソッドをつかって
numberに6を代入してくれます(0から数え始めるため)
そしてnumberに1を足して7になり
numberのインデックスを持つjapanese_listのリストの要素である「く」を
letterに代入してくれます

#ファイルの出力
以下のサイトを参照しました

f = open('letter.txt', 'w')
f.write(letter)
f.close()

これによってletter.txtに次の新しい文字が出力されます

#これでできます
丸ごとコピーしてください

japanese_list = ["","","","","",\
         "","","","","",\
         "","","","","",\
         "","","","","",\
         "","","","","",\
         "","","","","",\
         "","","","","",\
         "","","",\
         "","","","","",\
         "","",""]

f = open('letter.txt') 
letter = f.read()  
f.close()

number = japanese_list.index(letter)
number = number + 1
letter = japanese_list[number]

f = open('letter.txt', 'w')
f.write(letter)
f.close()

これを実行すると
letter.txtにもともと「あ」が入っていると
「い」をだしてくれます

0
0
3

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