Skip to main content
 首页 » 编程设计

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

2025年05月04日12arxive

我无法将文本文件中的数字添加到我的列表中,也不知道如何添加。

到目前为止的代码:

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 - 文件编辑可能比我在这里展示的更智能。