2017-02-05 116 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')) 

这应该输出一个列表文件的每一行作为它自己的列表中的索引,但它不会被分开。该文件的整行将是该列表中的索引

相关问题