【问题标题】:Why is Python giving me "an integer is required" when it shouldn't be?为什么 Python 不应该给我“需要整数”?
【发布时间】:2012-03-10 09:20:15
【问题描述】:

我的 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

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

为什么会有问题?

【问题讨论】:

  • print(n) 更改为print(repr(n), type(n))。输出可能很有启发性。
  • 在 Python 中,UpperCase 用于类,lower_case 用于变量。

标签: python file load pickle


【解决方案1】:

您需要对字符串进行转义:字符串中的 \ 是转义字符。

要么转义斜线:

"C:\\KingsCapture\\Test\\List.txt"

或使用原始字符串:

r"C:\KingsCapture\Test\List.txt"

【讨论】:

  • 这点很好,我忘了那些和其他人在一起的。虽然这不是导致问题的原因,但我也应该改变它。 :P 谢谢
【解决方案2】:

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

【讨论】:

  • +1,或者可能只是认为from os import open 是必要的
  • @gnibbler:我只是在编辑评论,但你打败了我。 :^)
  • 原来如此,谢谢。由于之前的一个错误,我有 from os import *,但我忘了摆脱它。 -facepalm-谢谢! :D
【解决方案3】:

我敢打赌 n 是 1 而不是 "1"

尝试:

print(type(n))

我猜你会看到它是 int 而不是字符串。

File = open("C:\KingsCapture\Saves\\" + n + "\BF.txt", "w")

您不能添加整数和字符串来产生您收到的错误消息。

【讨论】:

  • 我认为在字符串中添加一个 int 会在 Python 2.7 中产生 TypeError: cannot concatenate 'str' and 'int' objects
  • 我专门将 n 设置为“1”、“2”、“3”或“4”,具体取决于按下的按钮
【解决方案4】:

正如 DSM 所指出的,您使用的是 http://docs.python.org/library/os.html#os.open 而不是内置的 open() 函数。

在 os.open() 中,第二个参数(模式)应该是整数而不是字符串。因此,如果您应该使用from os import *,那么只需将模式字符串替换为以下参数之一:

  • os.O_RDONLY
  • os.O_WRONLY
  • os.O_RDWR
  • os.O_APPEND
  • os.O_CREAT
  • os.O_EXCL
  • os.O_TRUNC

【讨论】:

  • 实际上,有了那个导入,他就不需要“os”了。对于常量。
猜你喜欢
  • 2022-01-07
  • 2019-06-09
  • 1970-01-01
  • 2022-01-16
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
相关资源
最近更新 更多