如何将变量写入python 3.7中的文件

时间:2019-05-27 13:46:58

标签: 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)

1 个答案:

答案 0 :(得分:0)

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

在您的情况下,应将所有调用(如write(p1,"Had",p1sc," points")替换为格式字符串,如write(f"{p1} Had {p1sc} points")(Python 3.6+)或write("{p1} Had {p1sc} points".format(p1=p1, p1sc=p1sc))(Python 3.5及更高版本)。

除此之外:

  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