一尘不染

为什么Python不应该给我一个“需要整数”的信息?

python

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

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)

在此,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

在外壳中执行相同的加载后,我没有收到任何错误:

>>> 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")

为什么会有问题?


阅读 289

收藏
2021-01-20

共1个答案

一尘不染

您可能从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

因此您使用了错误的打开功能。(我想您可以简单地完成from os import open,但是可能性较小。)通常,应避免这种导入样式global,在实际情况下应避免使用。

2021-01-20