2017-09-30 17 views
0

私の目標は、テスト平均の入力を求めてtxtファイルに書き込むことです。ループを使用してtests.txtファイルを読み込んで処理する2番目のプログラム最初のプログラムを2桁の表にしてテスト名とスコアを小数点以下1桁まで正確に表示します。Python - txtファイルからデータにアクセスする

txtファイルを読み取る2番目のプログラムはどのように見えますか?

def main(): 
    outfile =open('test.txt', 'w') 
    print('Entering six tests and scores') 
    num1 = float(input('Enter % score on this test ')) 
    num2 = float(input('Enter % score on this test ')) 
    num3 = float(input('Enter % score on this test ')) 
    num4 = float(input('Enter % score on this test ')) 
    num5 = float(input('Enter % score on this test ')) 
    num6 = float(input('Enter % score on this test ')) 

    outfile.write(str(num1) + '\n') 
    outfile.write(str(num2) + '\n') 
    outfile.write(str(num3) + '\n') 
    outfile.write(str(num4) + '\n') 
    outfile.write(str(num5) + '\n') 
    outfile.write(str(num6) + '\n') 
    outfile.close() 
main() 

そして、私の2番目のプログラム:ここ

は、最初のプログラムのための私のコードですべての

def main(): 
    infile = open('test.txt' , 'r') 
    line1 = infile.readline() 
    line2 = infile.readline() 
    line3 = infile.readline() 
    line4 = infile.readline() 
    line5 = infile.readline() 
    line6 = infile.readline() 
    infile.close() 
    line1 = line1.rstrip('\n') 
    line2 = line2.rstrip('\n') 
    line3 = line3.rstrip('\n') 
    line4 = line4.rstrip('\n') 
    line5 = line5.rstrip('\n') 
    line6 = line6.rstrip('\n') 
    infile.close() 
main() 
+0

だから問題は何ですか? – Mureinik

+0

あなたの.txtのすべての行を次のように置くことができます: [xはiをに] – Primusa

+0

各テストスコアの名前を追加する際のヒントはありますか? –

答えて

2

まず、そのように自分自身を繰り返す必要は間違いありません - シンプルループはそのような繰り返しコードを書くのを防ぎます。それにもかかわらず、辞書(キー(名前)を値(スコア)にマッピングする必要があるような状況のためのデータ構造です)を使用することを検討することをお勧めします。また、コンテキストマネージャーとしてwithステートメントを使用することを検討することもできます。これは、ネストしたコードブロックの後に自動的にファイルを閉じるためです。

ので、アカウントにすべてのことを取って、次の行に沿って何かは、トリックを行う必要があります。

def first(): 

    print('Entering six tests and scores') 

    my_tests = {} 

    for i in range(6): 
     name, score = input('Enter name and score, separated by a comma: ').split(',') 
     my_tests[name] = round(float(score), 1) 

    with open('tests.txt', 'w') as f: 
     for name, score in my_tests.items(): 
      f.write('{} {}\n'.format(name, score)) 

を...そして、それはあなたの問題の第二の部分に来る:

def second(): 

    with open('tests.txt', 'r') as f: 
     tests = f.readlines() 

     for row in tests: 
      test = row.rstrip('\n').split() 
      print('{}\t{}'.format(test[0], test[1])) 
+0

また、@mentalitaは 'f = open(...) 'の代わりに' with'を使ってファイルを開きました。コンテキストマネージャは、例外を処理し、ファイルハンドルが閉じられます(ファイルが存在しない場合はキャッチする必要はなく、 'f.close()'を呼び出すことを心配しています)。 –

関連する問題