如何将用户输入的号码添加到我的文本文件列表中?

时间:2016-04-29 20:20:12

标签: python

我无法在我的列表中添加一个数字,我在文本文件中并且不知道如何操作。

到目前为止

代码:

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,J.bloggs@anemailaddress.com,01269 512355, 1, 0, 0, 0, 
                                                        ^  

除了已经存在的数字之外,我想要添加此数字的值是0,由下面的箭头指示。文本文件名为players.txt,如图所示。

完整的代码答案会有所帮助。

2 个答案:

答案 0 :(得分: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

  3. 你不会指望这是一个很大的问题,但确实如此。

    另一个提示:可能想检查模块csv - 文件编辑可能比我在这里显示的更聪明。

答案 1 :(得分:-1)

2个问题,首先,您永远不会将更改保存到文件中。你需要构建字符串然后用L.write(“你的新字符串”)保存它。其次,您需要在添加点之前将点转换为整数,更改

new_points = string[7] + points

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

编辑:修复了评论中提到的语法