Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

file - Why is Python giving me "an integer is required" when it shouldn't be?

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:KingsCaptureSaves" + n + "BF.txt", "w")
    pickle.dump(BF, File)
    File = open("C:KingsCaptureSaves" + n + "WF.txt", "w")
    pickle.dump(WF, File)
    File = open("C:KingsCaptureSaves" + n + "PBList.txt", "w")
    pickle.dump(PBList, File)
    File = open("C:KingsCaptureSaves" + 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:KingsCaptureSaves" + n + "BF.txt", "w")
TypeError: an integer is required

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

>>> File = open("C:KingsCaptureTestList.txt", "r")
>>> File = open("C:KingsCaptureTestList.txt", "w")
>>> n = "1"
>>> File = open("C:KingsCaptureSaves" + n + "BF.txt", "r")
>>> File = open("C:KingsCaptureSaves" + n + "BF.txt", "w")

Why is this having a problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...