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

标签 python python-3.x 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+”。请注意,如果该文件已存在,那么它将覆盖现有文件。以下是更多信息的链接:https://www.tutorialspoint.com/python3/python_files_io.htm 。另外,想想ahed87 的评论。 我希望,它会有所帮助。 p.s:新的编辑来改进答案

关于python - 如何在 python 3.5 中将文件内容添加到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47485278/

相关文章:

python - 字符串列表的总和引发 TypeError

python - 使用 Python 和 pyparsing 解析 Visual Basic 函数的参数列表

Python3 : Writing data of bytes in a file

python - 如何在 matplotlib 中根据 x、y、z 坐标绘制等高线图? (plt.contourf 或 plt.contour)

python - Windows 上的导入和路径名

Python 3.2 与 Python 2.7 代码问题

python - 在 python3 中计算季度的巧妙方法

python - 在 if 语句下将字符串附加到新列表

python - 处理Python中的按键错误

Python - 在 "detached"进程中生成函数的最佳方式