1

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?

1

2 Answers 2

4

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:

with open('background_tiles.txt', 'r') as f:
    contents = f.readlines()

for line in contents:
    for c in line.split():
        self.type = int(c)

The with is 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. readlines will read the file into a list (each line represented as a list element), and split() splits on the space.

Sign up to request clarification or add additional context in comments.

Comments

3

Your line contains string like - "1 0 1 0 1 0". You need to split your line on space: -

for string in line.split():
    self.type = int(string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.