Why is Python giving me “an integer is required” w

2019-01-26 10:23发布

I have a save function within my Python program which looks like this:

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)

Here, n is "1".

I get an error looking like this:

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

Upon doing the same loading within the shell, I get no errors:

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

Why is this having a problem?

4条回答
家丑人穷心不美
2楼-- · 2019-01-26 11:02

I'll bet that n is 1 not "1".

try:

print(type(n))

I'll guess that you'll see its an int not a string.

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

You can't add ints and strings producing the error message you are getting.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-26 11:07

You need to escape your strings: a \ in a string is an escape character.

Either escape the slashes:

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

or use Raw strings:

r"C:\KingsCapture\Test\List.txt"
查看更多
我命由我不由天
4楼-- · 2019-01-26 11:15

You probably did a star import from the os module:

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

so you're using the wrong open function. (I suppose you could've simply done from os import open, but that's less likely.) In general this import style should be avoided, as should use of global, where practical.

查看更多
做自己的国王
5楼-- · 2019-01-26 11:25

As DSM noted, you're using http://docs.python.org/library/os.html#os.open instead of built-in open() function.

In os.open() the second parameter (mode) should be integer instead of string. So, if you ought to use from os import * then just substitute mode string with one of the following args:

  • os.O_RDONLY
  • os.O_WRONLY
  • os.O_RDWR
  • os.O_APPEND
  • os.O_CREAT
  • os.O_EXCL
  • os.O_TRUNC
查看更多
登录 后发表回答