如何将文件内容添加到 python 3.5 中的变量

how to add a file contents to a variable in python 3.5

我不是很有经验所以请知道我正在尽我所能。如何将文件的第一个内容(例如 65)添加到新输入的数字,然后覆盖文件以保存它?

非常感谢任何建议。 这是我的编程:

henry = 0
emily = 0
george = 0
points = 0

file = open('nfc.txt','r+')
for line in file: 
    print(line)

if input("Who would you like to give points to? ") == "henry":
    points = int(input("How many points would you like to give to Henry? "))
    henry = henry + points
    print("Henry now has",henry, "points")
    points = 0
    file.write(str(henry)+" ")
    file.write(str(emily)+" ")
    file.write(str(george)+" ")
    file.close()

else:
    print("That name is not valid")

当目录中存在 'nfc.txt' 时,您的代码可以正常工作。如果文件不存在,则使用 'w+'。请注意,如果该文件已经存在,那么它将覆盖现有文件。这里是 link 以获取更多信息:https://www.tutorialspoint.com/python3/python_files_io.htm。另外,想想 ahed87 的评论。 我希望,它会有所帮助。 p.s:改进答案的新编辑

假设我理解您的问题,这应该可以解决。它打开文件并获取值,然后将用户输入附加到它们并将它们写入文件。我已经评论了它以防你迷路我希望这对你有所帮助。

file = open('nfc.txt', 'r+') ### opens file
f = file.read() ### reads file and assigns it to variable f
f = f.splitlines() ### slits file into list at any neline "\n"
scores = {} ### creates dictionary to store data


for line in f:
    line = line.replace(':', '') ### replaces colons with nothing
    line = line.split() ### splits name from score
    scores[line[0]] = int(line[1]) ###appends dictionary so name is key and score is values

name = input("Who would you like to give points to?").lower() ### user input
if name in scores.keys(): ### checks to see if input is a dict key
    point = int(input(
            "How many points would you like to give to {}?".format(name))) ### formats name into next input question
    scores[name] += point ### adds value to current score
    scores['total'] += point ### adds value to change total

    file.seek(0) ### sets position in file to start
    file.truncate() ### deletes all data in current file
    for key in list(scores.keys()): ### gets all keys from dict to ittereate
        file.write("{}: {}\n".format(key, str(scores[key]))) ### writes info to file with \n for new person
    file.close() ### closes file IMPORTANT

else:
    print("That name is not valid")

我希望你不介意滚动评论我知道它不是很 pythonic

现在可以使用了

你必须使用'w'写入文件

henry = 0
emily = 0
george = 0
points = 0

file = open('nfc.txt', 'w+')
for line in file:
    print(line)

if input("Who would you like to give points to? ") == "henry":
    points = int(input("How many points would you like to give to Henry? "))
    henry = henry + points
    print("Henry now has", henry, "points")
    points = 0
    file.write(str(henry) + " ")
    file.write(str(emily) + " ")
    file.write(str(george) + " ")
    file.close()

else:
    print("That name is not valid")

在文件中你得到了这个