2017-02-05 53 views
-1

爲了創建一個遊戲的迷你項目,我正在開發一個函數,該函數應該返回一行棋盤(在遊戲中),每行不包含換行符董事會通過打開和閱讀文件。正確讀取每行一行的文件的方法

但不是調用文件我只是嘗試該python閱讀它避免使用打開的文件方法。所以我首先嚐試的是爲這個函數創建一個循環,但是某些東西一定是錯誤的,因爲當我測試這個函數時會出現錯誤信息。

「名單」對象有沒有屬性「分裂」

你能幫我這個功能。我目前的進展是這樣的,但我有點卡在這一點上,因爲我不知道什麼是錯的。

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 
+3

'board_list_of_lists'被聲明爲列表,並且不能拆分'list'對象(這是錯誤中提到的) –

+0

可能的重複項:[如何讀取大文件,在python中逐行](http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python) –

+0

board_file中的行看起來像什麼? –

回答

0

試試這個:

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 
0

不需要拆如果文件中的每一行是物理上的文件在自己的線路。

只要做到:

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 

然而,包括「\ n」在每行的末尾,所以只是改變環路追加太行:

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

這應該輸出一個列表文件的每一行作爲它自己的列表中的索引,但它不會被分開。該文件的整行將是該列表中的索引

相關問題