-4

I am trying to write numbers into a txt file. But i get the error message telling me that the values have to be in string format not in int.

a = [1,2,3,4,5]
b = [2,6,4,3,2]
with open('writefile.txt','w') as f:
     for i in range(len(a)):
     f.write (a[i])
f.close()

Can someone help me ? Thanks a lot

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
  • Please check the intends of your code. I think there are tabs xor spaces missing. And try a cast to a string. – H. Pauwelyn Apr 06 '18 at 16:45
  • 3
    Possible duplicate of [Converting integer to string in Python?](https://stackoverflow.com/questions/961632/converting-integer-to-string-in-python) – JJJ Apr 06 '18 at 16:47
  • 1) `with` makes the call to `close` unnecessary. 2) In Python a loop over an iterable is done using `for item in a:`. The index `i` is not Pythonic. –  Apr 06 '18 at 17:11
  • for... in range(len(...)) is very unpythonic. Use for... in a instead. – Jasper Apr 06 '18 at 17:14

2 Answers2

1

You could convert the int to a string before writing:

Replace:

f.write (a[i])

With:

f.write (str(a[i]))
-1

Here a short answer : the value that you want is 'w' which is a string but in line 3-5 you are executing code for integer using the list,length and index of list Rather than this try to code: write() with an string Then It will work