I have a text file:
1 0 1 0 1 0
1 0 1 0 1 0
1 0 1 0 1 0
1 0 1 0 1 0
I want to be able to retrieve each string and convert it to an integer data type but my piece of code results in ValueError: invalid literal for int() with base 10: ''
tile_map = open('background_tiles.txt','r');
for line in tile_map:
for string in line:
self.type = int(string);
What is the correct way to retrieve the data and convert it successfully?
One thing to remember when iterating through the file is that the newline character is included, and when you try to cast that using
int(), you will receive the error you are referencing (because Python doesn’t know how to convert it into an integer). Try using something like:The
withis a context manager, and it is generally a more efficient way to deal with files as it handles things like closing for you automatically when it leaves the block.readlineswill read the file into a list (each line represented as a list element), andsplit()splits on the space.