【发布时间】:2021-07-28 08:50:27
【问题描述】:
我有一个文件如下:
cat file.txt
# unimportant comment
# unimportant comment
# unimportant comment
# important line
blah blah blah
blah blah blah
# insignificant comment
# significant comment
xyz
xyz
我想打印以'#' 开头的行,前提是以下行没有被注释。
我希望提取以下两行:
# important line
# significant comment
我尝试了以下方法,但它不起作用:
with open("file.txt","r") as fp:
for line in fp:
if line[0] == '#':
pos = fp.tell()
previous_line_comment = True
elif line[0] != '#' and previous_line_comment:
fp.seek(pos)
print(fp.readline())
previous_line_commented = False
else:
fp.readline()
【问题讨论】: