问题描述
cat file.txt
# unimportant comment
# unimportant comment
# unimportant comment
# important line
blah blah blah
blah blah blah
# insignificant comment
# significant comment
xyz
xyz
我想打印以 '#'
开头的行,仅当以下行没有被注释时。
我希望提取以下两行:
@H_502_6@# 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()
解决方法
让我们在迭代时存储每条评论的值,然后在遇到不是评论的行时输出前一行。
with open('test.txt','r') as file:
## Set previous comment to None,we will store the comment in here
previous_comment = None
for line in file.readlines():
## We use startswith to return a boolean T/F if the string starts with '#'
line_is_comment = line.startswith('#')
if line_is_comment:
## If the current line is a comment,set the previous comment to the current line
previous_comment = line
continue
elif previous_comment and not line_is_comment:
## If previous comment exists,and the current line is not a comment -> output
print(previous_comment)
previous_comment = None
else:
previous_comment = None
输出
# important line
# significant comment
,
&
是按位 AND 运算符。我相信您打算使用的是逻辑 AND。
elif line[0] != '#' and previous_line_comment: