0

I'm learning Python at the moment and I'm resolving easy problems to get the feeling of it.

I'm trying to read a text file and print the maze that is inside of it:

##########
##---##--#
#--------#
#---###--#
#--------#
##-------#
##########

For now I have the following:

file = open("maze.txt", "r")
maze = file.readlines()
print(maze)

for i in range(len(maze)):
    for j in range(len()):
        print(maze[i][j])

file.close()

I want to be able to have acess to every single character inside the file, so my goal for now is to print it one by one. But I have no idea what to write inside the range of the second for loop.

I know it's kind of a dumb question, but I'm really stuck. Thank you!

Hugo Novais
  • 69
  • 1
  • 7
  • You can't call `len()` with no argument. Are you asking about the resultant error? Or is the code you're running different from the code you posted? – Tom Karzes Nov 03 '22 at 23:25
  • 3
    FYI `file.close` should be `file.close()` but the better approach is to use a [context manager](https://realpython.com/python-with-statement/). – jarmod Nov 03 '22 at 23:25
  • Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – teedak8s Nov 03 '22 at 23:28
  • 1
    As long as you are learning python, you should get out of the habit of using `range()` in loops unless you really need to. Here you can just use `for line in file:` and then `for character in line:`. It saves a lot of indexing errors. – Mark Nov 03 '22 at 23:32
  • @Mark It prints nothing. Is it something wrong with my code? I'm using `print(maze[line][character])` – Hugo Novais Nov 03 '22 at 23:39
  • If you loop this way, you just `print(character)`. Or `print(character, end='')` if you don't want to print a new line with each call.. – Mark Nov 03 '22 at 23:40
  • It still prints nothing – Hugo Novais Nov 03 '22 at 23:44
  • https://stackoverflow.com/a/10422970/797495 - https://trinket.io/python3/0a76feae6b – Pedro Lobito Nov 03 '22 at 23:57

2 Answers2

0

You are on the right track. In the second for loop you have the line i, so you should do range(len(maze[i])) in order to do print(maze[i][j].

foobarna
  • 854
  • 5
  • 16
0

Thanks to some of the comments I was able to come to a solution

Instead of having

for i in range(len(maze)):
    for j in range(len()):
        print(maze[i][j])

I could replace it with this:

for line in maze:
    for char in line:
        print(char)

Thank you all!

Hugo Novais
  • 69
  • 1
  • 7