2016-04-29 13 views
2

私はテキストファイルにある私のリストに番号を追加することができません。これまで入力した番号をテキストファイルリストに追加するにはどうすればよいですか?

コード:

def add_player_points(): 
# Allows the user to add a points onto the players information. 

    L = open("players.txt","r+") 
    name = raw_input("\n\tPlease enter the name of the player whose points you wish to add: ") 
    for line in L: 
      s = line.strip() 
      string = s.split(",") 
      if name == string[0]: 
        opponent = raw_input("\n\t Enter the name of the opponent: ") 
        points = raw_input("\n\t Enter how many points you would like to add?: ") 
        new_points = string[7] + points 
    L.close() 

これは、テキストファイルのキーのサンプルです。約100は、ファイル内にあります。

Joe,Bloggs,[email protected],01269 512355, 1, 0, 0, 0, 
                 ^ 

私はこの番号が追加されたい値がその下矢印そこではすでに数、ほか0です。テキストファイルは図のようにplayers.txtと呼ばれています。

完全なコードの回答が役に立ちます。

答えて

0

を述べたように、私が何を好きではなかったの構文を修正しました私は前に書いたが、ユースケースはfileinputには最適ではない。私はソースから同様のコードを取り出して、あなたのニーズに合ったものにしました。

修正する行ごとに、ファイル全体を書き直していることに注意してください。パフォーマンスが懸念される場合は、データを扱う方法を変更することを強くお勧めします。

このコードは次のとおりです。

from tempfile import mkstemp 
from shutil import move 
from os import remove, close 

def add_player_points(): 
    file_path = "test.txt" 
    name = raw_input("\n\tPlease enter the name of the player whose points you wish to add: ") 
    #Create temp file 
    fh, abs_path = mkstemp() 
    with open(abs_path,'w') as new_file: 
     with open(file_path) as old_file: 
      for line in old_file: 
       stripped_line = line.strip() 
       split_string = stripped_line.split(",") 
       print name == split_string[0] 
       if name == split_string[0]: 
        opponent = raw_input("\n\t Enter the name of the opponent: ") 
        points = raw_input("\n\t Enter how many points you would like to add?: ") 
        temp = int(split_string[5]) + int(points) # fool proofing the code 
        split_string[5] = str(temp) 
        stripped_line = ','.join(split_string)# line you shove back into the file. 
        print stripped_line 
        new_file.write(stripped_line +'\n') 
       else: 
        new_file.write(line) 
    close(fh) 
    #Remove original file 
    remove(file_path) 
    #Move new file 
    move(abs_path, file_path) 
  1. Search and replace a line in a file in Python

  2. Editing specific line in text file in python

あなたはそれが問題のその大きなことを期待していないが、それはあります。

もう1つのヒント:モジュールcsvをチェックしたいと思うかもしれません - 私がここに示したものよりもファイル編集のほうがスマートになるかもしれません。

+0

このコードは私のテキストファイルを削除します。 Iveはそれを使って周りを試してみたが役に立たなかった:( – Toby

+0

助けをありがとう:)ありがとう – Toby

-1

2問題は、最初にファイルに変更を保存することはありません。文字列を作成し、最後にL.write( "新しい文字列")で保存する必要があります。第二に、あなたは

new_points = string[7] + points 

new_points = int(string[7]) + int(points) 

にある[編集]を変更、追加する前に、int型にポイントをキャストする必要があります。コメントで

+1

関数呼び出しの構文をもう一度見てみることをお勧めします。 – TigerhawkT3

+0

'new_points = int(string [7])+ int(points)' – Olegp

関連する問題