python - 如何将用户输入的数字添加到我的文本文件列表中?

标签 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() 

这是文本文件中的 key 示例。文件中大约有100个:

Joe,Bloggs,J.bloggs@anemailaddress.com,01269 512355, 1, 0, 0, 0, 
                                                        ^  

我希望将此数字添加到的值是 0 以及已经存在的数字,由其下方的箭头指示。如图所示,文本文件名为 players.txt

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

最佳答案

我不喜欢我之前写的东西,而且这个用例对于 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

您不会认为这是一个大问题,但事实确实如此。

另一个提示:可能需要检查模块 csv - 文件编辑可能比我在这里展示的更智能。

关于python - 如何将用户输入的数字添加到我的文本文件列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36946808/

相关文章:

python - 如何在矩阵中查找单元格邻居

python - 如何使用 python 转置和自动填充数据框?

python - 获取脚本目录名称 - Python

python - 一个大正则表达式是否比一堆小正则表达式更有效?

python - mac os 中的 pygame 安装问题

python - 如何在 pyGTK 中设置小部件的默认样式?

python - Popen 等待子进程,即使直接子进程已经终止

python - 使用模型推断批处理与使用 pytorch 的个人时的不同结果

python - Pandas如何获取行的索引?

python - Python 循环中的索引错误