简体   繁体   English

如何在文件中添加数字

[英]How to add numbers to a file

I'm a beginner at Python and I just learned about opening files, reading files, writing files, and appending files.我是 Python 的初学者,我刚刚学会了打开文件、读取文件、写入文件和附加文件。

I would I like to implement this to a little project that I'm making that asks for the user's name and appends it to a txt file named "HallOfFame.txt"我想将此实现到我正在制作的一个小项目中,该项目要求用户提供用户名并将其附加到名为“HallOfFame.txt”的 txt 文件中

try:
    infile = open('HallOfFame.txt', 'r')
    file_contents = infile.read()
    print(file_contents)
    infile.close()
except:
    FileNotFoundError
    print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")

name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + '\n')
name_file.close()

Everytime someone adds their name, I'd like it to become something like this:每次有人添加他们的名字时,我希望它变成这样:

  1. Vix维克斯
  2. Mike麦克风
  3. Valerie瓦莱丽

Something similar like that (above) where they have to run the program again to see the Hall of Fame.类似的东西(上图)他们必须再次运行程序才能看到名人堂。

Thank you!谢谢!

I can understand your question.我能理解你的问题。 you can try using the JSON module and do something like this.您可以尝试使用 JSON 模块并执行类似的操作。

import json

list = [1, "Vix"]

with open ('HallOfFame.txt', 'w') as filehandle:
     json.dump(list, filehandle)

here you can update the list every time you get input.每次收到输入时,您都可以在此处更新列表。 and write it to the text file.并将其写入文本文件。 but the appearance will look like this.但外观会是这样的。

[1, "Vix"] 
[2, "Mike"]
[3, "Valerie"]
count = 0
try:
    infile = open('HallOfFame.txt', 'r')
    file_contents = infile.readlines()
    if len(file_contents) != 0:
        print("\nHall of Fame")
        for line in file_contents:
            count += 1
            print("{}. {}".format(count, line.strip()))
    print()
    infile.close()
except:
    FileNotFoundError
    print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")

name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + "\n")
name_file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM