为什么Python不应该给我"需要一个整数"?

use*_*917 7 python load file pickle

我的Python程序中有一个save函数,如下所示:

def Save(n):
    print("S3")
    global BF
    global WF
    global PBList
    global PWList
    print(n)
    File = open("C:\KingsCapture\Saves\\" + n + "\BF.txt", "w")
    pickle.dump(BF, File)
    File = open("C:\KingsCapture\Saves\\" + n + "\WF.txt", "w")
    pickle.dump(WF, File)
    File = open("C:\KingsCapture\Saves\\" + n + "\PBList.txt", "w")
    pickle.dump(PBList, File)
    File = open("C:\KingsCapture\Saves\\" + n + "\PWList.txt", "w")
    pickle.dump(PWList, File)
Run Code Online (Sandbox Code Playgroud)

这里,n是"1".

我收到一个如下错误:

  File "C:/Python27/KingsCapture.py", line 519, in Save
    File = open("C:\KingsCapture\Saves\\" + n + "\BF.txt", "w")
TypeError: an integer is required
Run Code Online (Sandbox Code Playgroud)

在shell中执行相同的加载时,我没有得到任何错误:

>>> File = open("C:\KingsCapture\Test\List.txt", "r")
>>> File = open("C:\KingsCapture\Test\List.txt", "w")
>>> n = "1"
>>> File = open("C:\KingsCapture\Saves\\" + n + "\BF.txt", "r")
>>> File = open("C:\KingsCapture\Saves\\" + n + "\BF.txt", "w")
Run Code Online (Sandbox Code Playgroud)

为什么这有问题?

DSM*_*DSM 15

你可能从os模块导入了一个星形:

>>> open("test.dat","w")
<open file 'test.dat', mode 'w' at 0x1004b20c0>
>>> from os import *
>>> open("test.dat","w")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required
Run Code Online (Sandbox Code Playgroud)

所以你使用了错误的开放功能.(我想你可以简单地完成from os import open,但这不太可能.)一般来说,应该避免使用这种导入样式global,在实际应用中应该使用.