在Python中,如何使用“ strip()for file in file”格式仅读取文件的前x行?

时间:2019-01-05 14:15:19

标签: python

请参见下面的代码,我尝试使用2种不同的功能从文本文件(基本上是游戏板的保存文件)中读取不同的部分。第一个尝试读取前5行并将它们分配给矩阵(列表列表)。第二个尝试读取第6行并将其分配给字符串。但是我似乎无法使代码正常工作。有什么想法吗?

def load_board():
    with open("savefile.txt","r") as savefile:
        loadBoard = [line.strip().split(",") for line in savefile]
        return loadBoard

def load_side():
    with open("savefile.txt","r") as savefile:
        loadBoard = [line.strip() for line in savefile]
        loadSide = loadBoard.pop()
        return loadSide

savefile.txt看起来像这样:

R,R,R,M,R
R,R,R,R,-
R,R,M,R,R
R,R,R,R,R
M,R,R,R,R
M

5 个答案:

答案 0 :(得分:1)

在两个功能中,您正在读取完整文件。您需要阅读所有行,然后使用必填行,请参见以下示例:

def load_board():
    with open("savefile.txt","r") as savefile:
        lines = savefile.readlines()
        loadBoard = [line.strip().split(",") for line in lines[:5]]
        loadside = lines[6]
        return loadBoard, loadside

答案 1 :(得分:1)

与其在每个函数中打开文件,不如将已经打开的文件作为参数:

import itertools

# Pre-condition: the input is at the beginning of the file
def load_board(savefile):
    return [line.strip().split(",") for line in itertools.islice(savefile, 5)]


# Pre-condition: the first 5 lines have already been read
def load_side(savefile):
    return next(savefile).strip()

然后在调用每个函数之前先打开文件 。请注意,应使用load_from_file来确保以正确的顺序调用load_boardload_side,并且不会从savefile进行其他读取来破坏先决条件。

def load_from_file(fname):
    with open(fname) as savefile:
        board = load_board(savefile)
        side = load_side(savefile)
    return board, side

loadBoard, loadSide = load_from_file("savefile.txt")

答案 2 :(得分:0)

如代码中的

savefile是文件实例,而不是行列表。而是对所有行使用savefile.readlines()。另外,

loadBoard = [line.strip().split(",") for line in savefile.readlines()]

将为您提供全部6行,而不仅仅是5行。因此loadBoard[-1]将是[M]

答案 3 :(得分:0)

为什么不一次加载文件,然后使用输出解析出您想要的内容?

def load_save(save_filename):
    with open(save_filename, 'r') as save_file:
        return save_file.read().split('\n')  # Return a list of all lines from the save file

def load_board(save_lines):
    return [line.strip().split(',') for line in save_lines[:5]]  # Won't include last line (side line)

def load_side(save_lines):
    return [save_lines[5:].strip()] # Just the last line

可以这样使用:

save_lines = load_save('savefile.txt')
board = load_board(save_lines)
side = load_side(save_lines)

答案 4 :(得分:0)

您也可以enumerate覆盖文件对象。

def load_board():
    with open("savefile.txt","r") as savefile:
        loadBoard = [line.strip().split(",") for i, line in enumerate(savefile) if i<=4]
        return loadBoard

def load_side():
    with open("savefile.txt","r") as savefile:
        loadBoard = [line.strip() for i, line in enumerate(savefile) if i==5]  #only 6th ( index starts at 0 )
        loadSide = loadBoard.pop()
        return loadSide

print(load_board())
print(load_side())

输出

[['R', 'R', 'R', 'M', 'R'], ['R', 'R', 'R', 'R', '-'], ['R', 'R', 'M', 'R', 'R'], ['R', 'R', 'R', 'R', 'R'], ['M', 'R', 'R', 'R', 'R']]
M