如何将变量写入python3.7文件

2024-09-29 06:23:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在保存python的一个分数文件,但它出现了一个错误 当我试图保存一个由用户创建并在整个程序中更改的变量时

我试图改变它,但没用

def CreateFile():
   global CreateFile
   CreateFile = open("Score.txt", "w")
   CreateFile.write(p1,"Had",p1sc," points") 
   CreateFile.write(p2,"Had",p2sc," points")
   if p1sc > p2sc:
      CreateFile.write(p1," won with",p1sc," points")
      CreateFile.write(p2," lost with",p2sc," points")
   elif p2sc > p1sc:
      CreateFile.write(p2," won with",p2sc," points")
      CreateFile.write(p1," lost with",p1sc," points")

print("The score's have been saved in a file called 'Score.txt' ")
CreateFile()

p1和p2是输入变量 p1sc和p2sc是可以改变的变量

我收到的错误消息是:

  Exception has occurred: TypeError
write() takes exactly one argument (4 given)
  File "/Users/joshua/Desktop/aaHomeProjects/Programming/PythonProjects/DiceGame2ElecticBoogaloo.py", line 248, in CreateFile
    CreateFile.write(p1,"Had",p1sc," points")
  File "/Users/joshua/Desktop/aaHomeProjects/Programming/PythonProjects/DiceGame2ElecticBoogaloo.py", line 261, in <module>
    CreateFile()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)

Tags: runnameinpywithlinepointsfile
1条回答
网友
1楼 · 发布于 2024-09-29 06:23:18

您得到的特定错误是由于错误地使用了file.write()。与print()不同的是,file.write()需要一个字符串参数,而print()接受任意数量的位置参数并自动将它们与空格连接起来。你知道吗

在您的例子中,应该用write(f"{p1} Had {p1sc} points")(Python 3.6+)或write("{p1} Had {p1sc} points".format(p1=p1, p1sc=p1sc))(Python 3.5及更早版本)等格式字符串替换所有write(p1,"Had",p1sc," points")等调用。你知道吗

除此之外:

  1. 请参阅关于全局名称的注释。一般来说,尽可能避免声明全局变量(例如,应将变量p1、p1sc、p2、p2sc作为参数传递),并注意函数和变量共享同一命名空间。如果给CreateFile赋值,将覆盖CreateFile()函数,并且不能再在同一作用域中调用CreateFile()

  2. 在Python中,打开文件时使用with块也是一种常见的做法,它会在完成后隐式关闭文件:

你知道吗

def CreateFile(p1, p1sc, p2, p2sc):
   with open("Score.txt", "w") as file:
       file.write(f"{p1} Had {p1sc} points")
       # etc

相关问题 更多 >