简体   繁体   English

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

[英]In Python, how can I read just the first x lines from a file using the “strip() for line in file” format?

See code below where I try to use 2 different functions to read different parts from a text file (essentially a save file for a game board). 请参阅下面的代码,我尝试使用2个不同的函数从文本文件中读取不同的部分(本质上是游戏板的保存文件)。 The first one tries to read the first 5 lines and assign them to a matrix (list of lists). 第一个尝试读取前5行并将它们分配给矩阵(列表列表)。 The second one tries to read the 6th line and assign it to a string. 第二行尝试读取第6行并将其分配给字符串。 However I can't seem to get the code to work. 但是,我似乎无法让代码工作。 Any ideas? 有任何想法吗?

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 looks like this: 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

in both functions you are reading complete file. 在这两个函数中,您正在阅读完整的文件 You need read all lines and then use required lines , see below example: 您需要阅读所有行,然后使用必需的行,请参阅下面的示例:

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

Instead of opening the file in each function, take an already open file as an argument: 不要在每个函数中打开文件,而是将已经打开的文件作为参数:

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()

Then open the file once before calling each function. 然后在调用每个函数之前打开文件一次 Note that load_from_file should be used to ensure that load_board and load_side are called in the correct order and with no other reads from savefile to break the pre-conditions. 请注意,应使用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")

savefile as in code, is a file instance, not a list of lines. savefile在代码中,是一个文件实例,而不是一个行列表。 Instead, use savefile.readlines() for all the lines. 相反,对所有行使用savefile.readlines() Also, 也,

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

would give you all 6 lines, not just 5. So loadBoard[-1] would be [M] . 会给你所有6行,而不只是5.所以loadBoard[-1]将是[M]

Why not load the file once and then use the output to parse out what you want? 为什么不加载文件一次然后使用输出来解析你想要的?

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

This can be used like so: 这可以这样使用:

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

You can also enumerate over the file object. 您还可以枚举文件对象。

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())

Output 产量

[['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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我尝试在 Python 的文本文件中逐行解析,但它只能解析第一行,无法从第二行读取 - I try to parse line by line within a text file in Python , but it just can parse first line, it can not read from second line 你如何使用python只读取每行文件的第一个单词? - How can you read just the first word of every line of file using python? 我如何使用 Python 读取 n 行,其中 n 是文件中的第一行? - How would I read n lines where n is the first line in a file using Python? 我们如何从文件的行中读取浮点值? - How can we Read just float values from the lines of a file? 我如何从 python 中的 filei 读取前 10 行和最后 10 行 - How i can read the first 10 lines and the last 10 line from filei in python 如何使用python从文件中读取“开始”和“结束”标志之间的行 - How can I read the lines between the “start” and “end” flags from a file by using python Python 可以使用 \n 从文件中读取行并将其打印为 2 行吗? - Can Python read line from file with \n and print it in 2 lines? 如何使用 python 获取文件每一行的第一个单词? - How to get just the first word of every line of file using python? 使用python从文件中的特定行读取前几行 - read previous lines from specific line in a file using python 我如何从 python 中的特定行读取文本文件? - How i can Read text file from a specific line in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM