2012-02-19 44 views
6

我有我的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") 

这是为什么有问题?

+0

将'print(n)'改为'print(repr(n),type(n))'。输出可能是有启发性的。 – zwol 2012-02-19 23:17:01

+1

在Python中'UpperCase'用于类,'lower_case'用于变量。 – katrielalex 2012-02-19 23:21:29

回答

12

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

+0

+1,或者可能只是认为''从os导入open'是必要的 – 2012-02-19 23:24:24

+0

@gnibbler:我只是在编辑评论这个,但是你打败了我。 :^) – DSM 2012-02-19 23:25:54

+0

就是这样,谢谢。由于之前我有过一个错误,所以我从os导入*,并且忘记了它。 -facepalm- 谢谢! :D – user1048917 2012-02-20 00:06:14

3

您需要转义您的字符串:字符串中的\是一个转义字符。

要么逃避斜线:

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

或使用原始字符串:

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

这是一个好点,我忘了与其他人。虽然这不是导致问题的原因,但我也应该改变这一点。 :P谢谢 – user1048917 2012-02-20 00:17:02

0

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

尝试:

print(type(n)) 

我猜你会看到它的int不是一个字符串。

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

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

+0

向一个字符串添加一个int会产生'TypeError:无法在Python 2.7中连接'str'和'int'objects',我想。 – DSM 2012-02-19 23:28:28

+0

具体设置n为“1”,“2”,“3”或“4”,具体取决于按下的按钮 – user1048917 2012-02-20 00:04:09

2

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

在os.open()中,第二个参数(mode)应该是整数而不是字符串。所以,如果你应当用​​然后就替代模式串以下列参数的个数之一:

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

实际上,使用该导入,他不需要“os”。为常数。 – yak 2012-02-20 00:11:46

相关问题