-1

In order to create a mini project for a game I am developing a function which should returns one row of a board (in the words game) per line with newlines not included in the board by opening and reading a file.

But instead of calling the file I just try that python read it avoiding using the open file method. So what I tried firstly was create a loop for this function but something must be wrong cause an error message appears when I test this function.

'list' object has no attribute 'split'

Could you help me with this function. My current progress is this but I am a bit stuck at this point cause I don't know what could be wrong at all.

def read_board(board_file):
    """ 
    (file open for reading)  ->  list of list of str
    """
    board_list_of_lists = []
    for line in board_file:
        board_list_of_lists = board_list_of_lists.split('\n')
    return board_list_of_lists   
taoufik A
  • 1,279
  • 9
  • 20
Fence
  • 171
  • 10
  • 3
    `board_list_of_lists` is declared as list and you can not split `list` object (that's what mentioned in the error) – Anonymous Feb 05 '17 at 21:43
  • Possible duplicate of: [How to read large file, line by line in python](http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python) – Anonymous Feb 05 '17 at 21:44
  • What do the lines in board_file look like? – jeff carey Feb 05 '17 at 21:44
  • just one under the other – Fence Feb 05 '17 at 21:47
  • How should I proceed if lists cant be split them? Is there another method? – Fence Feb 05 '17 at 21:50
  • I mean what do the individual lines look like? Are they split by commas? What is an example line? – jeff carey Feb 05 '17 at 21:50
  • No. They are not split by commas. An example could be a word just under the other just like in a board. (Sorry I dont know how to write words under the other while typing in this comment box). – Fence Feb 05 '17 at 21:58
  • It might also help if the code of your function wasn't in a docstring...that way, your function actually *does* something... –  Feb 05 '17 at 22:23

2 Answers2

0

Try this instead:

def read_board(board_file):
    """ (file open for reading) -> list of list of str
    board_list_of_lists = []
    for line in board_file.split('\n'):
            board_list_of_lists.append(line)
    return board_list_of_lists  
jkdev
  • 9,037
  • 14
  • 52
  • 75
0

Don't need to split if each row in the file is physically on it's own line in the file.

Just do:

def read_board(board_file):
    board_list_of_lists = []
    for line in board_file:
        board_list_of_lists.append(line)
    return board_list_of_lists

However, that includes the '\n' at the end of each line, so just change the append line in the loop too:

board_list_of_lists.append(line.strip('\n'))

And that should output a list with each line of the file as its own index in the list, but it wont be separated. The entire row of the file will be an index in that list