[英]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_board
和load_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.