Why does Python give me an "integer required" when it shouldn't be?

I have a save function in my Python program that 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 message:

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

Performing the same load inside 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 does this have a problem?

+6
source share
4 answers

You probably imported an asterisk 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 

therefore you are using the wrong open function. (I suppose you could just do from os import open , but this is less likely.) In general, this import style should be avoided, as global should be used where practicable.

+12
source

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

Or output slashes:

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

or use the source lines:

 r"C:\KingsCapture\Test\List.txt" 
+3
source

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

In os.open (), the second parameter (mode) must be an integer, not a string. So, if you must use from os import * , then simply replace the mode line with one of the following arguments:

  • os.O_RDONLY
  • os.O_WRONLY
  • os.O_RDWR
  • os.O_APPEND
  • os.O_CREAT
  • os.O_EXCL
  • os.O_TRUNC
+2
source

I bet n - 1 not "1" .

to try:

 print(type(n)) 

I assume that you will see int not a string.

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

You cannot add ints and strings by creating the error message you receive.

0
source

Source: https://habr.com/ru/post/908857/


All Articles