仅当以下行未被注释时才提取注释行
extract the commented lines only if the following line is not commented
我有一个文件如下:
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()
&
是按位与运算符。我相信您打算使用的是合乎逻辑的 AND。
elif line[0] != '#' and previous_line_comment:
让我们在迭代时存储每条评论的值,然后在遇到不是评论的行时输出上一行。
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
我有一个文件如下:
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()
&
是按位与运算符。我相信您打算使用的是合乎逻辑的 AND。
elif line[0] != '#' and previous_line_comment:
让我们在迭代时存储每条评论的值,然后在遇到不是评论的行时输出上一行。
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