文件更好的辦法我有以下類型的文件:來劃分它有單獨的位置的標記在Python
--- part0 ---
some
strings
--- part1 ---
some other
strings
--- part2 ---
...
我想獲得的文件以Python列表的任何部分:
x = get_part_of_file(part=0)
print x # => should print ['some', 'strings']
x = get_part_of_file(part=1)
print x # => should print ['some other', 'strings']
所以,我的問題是什麼,是落實上述使用get_part_of_file
方法最簡單的方法。
我(醜)解決方案是象下面這樣:
def get_part_of_file(part, separate_str="part"):
def does_match_to_separate(line):
return re.compile("{}.*{}".format(separate_str, part)).match(line)
def get_first_line_num_appearing_separate_str(lines):
return len(list(end_of_loop() if does_match_to_separate(line, part) else line for line in lines))
with open("my_file.txt") as f:
lines = f.readlines()
# get first line number of the required part
first_line_num = get_first_line_num_appearing_separate_str(part)
# get last line number of the required part
last_line_num = get_first_line_num_appearing_separate_str(part + 1) - 1
return lines[first_line_num:last_line_num]